简体   繁体   English

Scala:案例类的静态val或def

[英]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. 我知道我可以向静态def / val的类中添加同伴对象,但是我的问题是我希望将其确认为特征。 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 我希望以抽象类型的形式访问此静态val或def(在这里,根据从java static预期的行为而言,请使用单词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"
}

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. 我希望能够在没有M实例的情况下以静态方法调用M.description。我的用例是我有M个对象的spark数据集,并且我想查看M的description属性而不从数据集中获取记录因为这将导致火花动作/作业。是否有可用于此的scala模式。 Thanks 谢谢

Just create a companion object for M which defines the static value and then reference that in the case class 只需为M创建一个伴随对象,该对象定义静态值,然后在case类中引用该对象

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
}

You can refactor description of B into another trait like: 您可以将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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM