Search code examples
scalaadt

Can I have a case class with default/hardcoded values


For example say I have a sealed trait AnimalSoundsand I have case class "Dog" and a case class "Cat" I want the two case classes value to default to "Woof" and "Cat"

sealed trait AnimalSounds extends Product with Serializable
final case class Dog(sound: String = "woof") extends AnimalSounds
final case class Cat(sound: String = "meow") extends AnimalSounds

println(Dog.sound) 

I get the error "sound is not a member of object"


Solution

  • If by "hardcoded" it is meant constants consider case objects like so

    sealed trait AnimalSounds { val sound: String }
    case object Dog extends AnimalSounds { val sound = "woof" }
    case object Cat extends AnimalSounds { val sound = "meow" }
    
    Dog.sound
    

    which outputs

    res0: String = woof