Scala: static val or def on case class

I know I can add a companion object to a class for static def/val but my problem is I want it to comfirm to a trait. I want access to this static val or def as an abstract type (using the word static here in terms of the behaviour expected from java static) Consider this code

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"
}

I want to be able to call M.description as a static method without having an instance of M. My use case is I have a spark dataset of M objects and I want to see the description property of M without getting a record from the dataset because that will result in a spark action / job Is there a scala pattern I can use for this. Thanks


Just create a companion object for M which defines the static value and then reference that in the case class

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

or assuming commonality between subtypes

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/82704.html

上一篇: std :: string如何实现?

下一篇: Scala:案例类的静态val或def