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.
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.
Kotlin Editor:
Previous: Data class point with destructuring declaration.
Next: Inline class email for type-safe email address representation.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics