Scala Program: Enum class for object color representation
Scala OOP Exercise-13 with Solution
Write a Scala program that creates an enum class Color with values for different colors. Use the enum class to represent an object's color.
Sample Solution:
Scala Code:
sealed trait Color
case object Red extends Color
case object Green extends Color
case object Blue extends Color
case object Orange extends Color
object ColorApp {
def main(args: Array[String]): Unit = {
val myColor: Color = Red
//val myColor: Color = Blue
printColor(myColor)
}
def printColor(color: Color): Unit = color match {
case Red => println("The color is Red.")
case Green => println("The color is Green.")
case Blue => println("The color is Blue.")
case Orange => println("The color is Orange.")
case _ => println("Unknown color.")
}
}
Sample Output:
The color is Red.
Explanation:
In the above exercise,
- First, we define a sealed trait "Color" that serves as the base type for different color objects. Then, we define case objects "Red", Green, and Blue that extend the Color trait to represent specific colors.
- The "ColorApp" object contains the “main()” method where we can test functionality. It assigns the "Red" color to the myColor variable and calls the "printColor()" method to print the color name.
- The "printColor()" method uses pattern matching to determine the specific color of the object and prints a corresponding message.
Scala Code Editor :
Previous: Destructuring declarations in point class.
Next: Class ContactInfo and customer with composition.
What is the difficulty level of this exercise?
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/scala-exercises/oop/scala-oop-exercise-13.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics