Enumerated types and extending existing types in Scala 2/3
scalaScala 2
Scala 2 doesn’t have an enum like Java, so Enumeration or case object are used. Besides, you can add fields to existing types by importing implicit class,
sealed trait Animal
object Animal {
case object Dog extends Animal
case object Cat extends Animal
}
object Converter {
implicit class AnimalConverter(animal: Animal) {
def hello() = animal match {
case Animal.Dog => "wan!"
case Animal.Cat => "nya!"
}
}
}
import Converter.AnimalConverter
object App {
def main() = {
print(Animal.Cat.hello) // nya!
}
}
Scala 3
enum and extension were added in Scala 3, so you can write as follows.
enum Animal:
case Dog, Cat
extension (animal: Animal) {
def hello() = animal match {
case Animal.Dog => "wan!"
case Animal.Cat => "nya!"
}
}
object App {
def main() = {
print(Animal.Cat.hello()) // nya!
}
}