w3resource

Kotlin Class: Enum class Color for Object color representation


Write a Kotlin program that creates an enum class 'Color' with values for different colors. Use the enum class to represent an object's color.


Pre-Knowledge (Before You Start!)

Before attempting this exercise, you should be familiar with the following concepts:

  • Enum Classes: A special class in Kotlin that represents a fixed set of constant values.
  • Data Classes: Kotlin classes that automatically generate useful functions like toString(), equals(), and hashCode().
  • Class Properties: Understanding how to define properties inside a Kotlin class.
  • Printing to Console: Using println() to display values.

Hints (Try Before Looking at the Solution!)

Try to solve the problem using these hints:

  • Hint 1: Define an enum class named Color with predefined color values.
  • Hint 2: Create a data class that includes a name property and a color property of type Color.
  • Hint 3: In the main() function, create instances of the data class with different colors from the enum class.
  • Hint 4: Use println() to display the name and color of each object.

Sample Solution:

Kotlin Code:

enum class Color {
    RED, GREEN, BLUE, BLACK, ORANGE
}

data class Object(val name: String, val color: Color)

fun main() {
    val plants = Object("Plants", Color.GREEN)
    val cloud = Object("Cloud", Color.BLACK)
    val flowers = Object("Flowers", Color.RED)

    println("${plants.name} color: ${plants.color}")
    println("${cloud.name} color: ${cloud.color}")
    println("${flowers.name} color: ${flowers.color}")
}

Sample Output:

Plants color: GREEN
Cloud color: BLACK
Flowers color: RED

Explanation:

In the above exercise -

  • First we define an enum class "Color" with different color values such as RED, GREEN, BLUE, BLACK, and ORANGE.
  • We also define a data class "Object" with properties name and color. The color property is of type Color in our enum class.
  • In the "main()" function, we create instances of the Object class representing different objects with their respective colors using enum values.
  • Finally, we print the name and color of each object using the println statement.

Go to:


PREV : Data class point with destructuring declaration.
NEXT : Inline class email for type-safe email address representation.

Kotlin Editor:


Improve this sample solution and post your code through Disqus

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.