0
votes

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"

3
I would suggest that you read the basis first of how to access members of a case class! - joesan
If you want that sound to behave like a constant that nobody could change and that is available without creating an instance, create it on the Companion object instead. - Luis Miguel Mejía Suárez

3 Answers

7
votes

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
2
votes

In order to work with a case class instance, you first need to create one:

val d: Dog = Dog()
println(d.sound)
0
votes

Since you have provided the defaults in your case class, you can also so

Dog().sound