我可以用 default/hardcoded 值的案例 class

Can I have a case class with default/hardcoded values

例如说我有一个密封的特性 AnimalSounds 我有一个案例 class "Dog" 和一个案例 class "Cat" 我希望这两种情况 classes 值默认为 "Woof" 和 "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) 

我收到错误 "sound is not a member of object"

为了使用案例 class 实例,您首先需要创建一个:

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

既然你已经提供了你的案例中的默认值class,你也可以这样

Dog().sound

如果 "hardcoded" 是指常量考虑 case objects 像这样

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

Dog.sound

输出

res0: String = woof