【问题标题】:Can I have a case class with default/hardcoded values我可以有一个带有默认/硬编码值的案例类吗
【发布时间】:2019-08-20 10:32:52
【问题描述】:

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

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

【问题讨论】:

  • 我建议你首先阅读如何访问案例类成员的基础!
  • 如果您希望声音表现得像一个没有人可以更改的常量,并且无需创建实例即可使用,请改为在 Companion 对象上创建它。

标签: scala adt


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

      由于您在案例类中提供了默认值,因此您也可以这样做

      Dog().sound
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-04-29
        • 1970-01-01
        • 2013-07-13
        • 1970-01-01
        • 2016-09-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多