0

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"

Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
SimonL
  • 3
  • 1

3 Answers3

7

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
Mario Galic
  • 47,285
  • 6
  • 56
  • 98
2

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

val d: Dog = Dog()
println(d.sound)
Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
0

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

Dog().sound
joesan
  • 13,963
  • 27
  • 95
  • 232