Scala:案例类的静态val或def

我知道我可以将一个伴侣对象添加到静态def / val的类中,但是我的问题是我想让它确定一个特性。 我想访问这个静态val或def作为抽象类型(根据java静态期望的行为使用static这个词)考虑这个代码

trait A {
  def aBehavior(): Unit
}
trait B {
  def bBehavior(): Unit
  def description: String
}

case class M extends A with B {
  override def aBehavior() = print("A behavior of M")
  override def bBehavior() = print("B behavior of M")
  override def description = "I'm M"
}

我希望能够将M.description作为静态方法调用,而不需要M的实例。我的用例是我有一个M对象的spark数据集,我希望看到M的description属性而不从数据集中获取记录因为这将导致一个火花行动/工作是否有一个我可以使用的scala模式。 谢谢


只需为M定义静态值,然后在案例类中引用它即可创建伴随对象

object M {
  val description = "I'm M"
}
case class M extends A with B {
  override def description = M.description
}

或假设亚型之间的共同性

trait Description {
  val title: String
  val description = s"I'm ${title}"
}
object M extends Description {
  val title = "M"
}
object N extends Description {
  val title = "N"
}
case class M() extends A with B {
  override def description = M.description
}
case class N() extends A with B {
  override def description = N.description
}

您可以将B描述重构为另一个特征,如:

trait BInfo {
  def description: String
}
trait B extends BInfo {
  def bBehavior(): Unit
  def bInfo: BInfo
  final override def description = bInfo.description
}
case class M() extends A with B {
  override def aBehavior() = print("A behavior of M")
  override def bBehavior() = print("B behavior of M")
  override def bInfo = M
}
object M extends BInfo {
  override def description = "I'm M"
}

val m = M()
M.description // I'm M
m.description // I'm M
链接地址: http://www.djcxy.com/p/82703.html

上一篇: Scala: static val or def on case class

下一篇: Scala immutable container class extended with mixins