首页 > 解决方案 > 我可以有一个带有默认/硬编码值的案例类吗

问题描述

例如,假设我有一个密封特征 AnimalSounds,我有一个案例类“Dog”和一个案例类“Cat”我希望这两个案例类的值默认为“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) 

我收到错误“声音不是对象的成员”

标签: scalaadt

解决方案


如果通过“硬编码”表示常量考虑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

推荐阅读