MOCKSTACKS
EN
Questions And Answers

More Tutorials









Scala Enumerations

Examples

Days of the week using Scala Enumeration


Java-like enumerations can be created by extending Enumeration.

object WeekDays extends Enumeration {
 val Mon, Tue, Wed, Thu, Fri, Sat, Sun = Value
}
def isWeekend(day: WeekDays.Value): Boolean = day match {
 case WeekDays.Sat | WeekDays.Sun => true
 case _ => false
}
isWeekend(WeekDays.Sun)
res0: Boolean = true

It is also possible to add a human-readable name for values in an enumeration:

object WeekDays extends Enumeration {
 val Mon = Value("Monday")
 val Tue = Value("Tuesday")
 val Wed = Value("Wednesday")
 val Thu = Value("Thursday")
 val Fri = Value("Friday")
 val Sat = Value("Saturday")
 val Sun = Value("Sunday")
}
println(WeekDays.Mon)
>> Monday
WeekDays.withName("Monday") == WeekDays.Mon
>> res0: Boolean = true

Beware of the not-so-typesafe behavior, wherein different enumerations can evaluate as the same instance type:

object Parity extends Enumeration {
 val Even, Odd = Value
}
WeekDays.Mon.isInstanceOf[Parity.Value]
>> res1: Boolean = true



Conclusion

In this page (written and validated by ) you learned about Scala Enumerations . What's Next? If you are interested in completing Scala tutorial, your next topic will be learning about: Scala Error Handling.



Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.


Share On:


Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.