使现有类在scala中实现traits

Luk*_*Feo 3 scala traits mixins

我有一个接受键值对的类,例如,它可以以map对象或case类的形式出现.让我们定义以下抽象:

 trait Reportable {
    def getAttributes : Map[String,Any]
  }
Run Code Online (Sandbox Code Playgroud)

我想要一个采用List [Reportable]的方法.可报告的可能实现是:

  • 实现本身的地图
  • 案例类我可以使用一些使用反射的东西从案例类中获取属性并将其放入地图中

问题是我无法弄清楚如何制作Product(所有案例类的基类)和Map类实现我的特性.我希望能够获取现有的类并混合可报告的特性,并根据类已有的方法实现它.

Sas*_*erg 8

我认为你不能混合这样的特质.

然而,imho,听起来像是EnrichMyLibrary Pattern的一个案例.示例Map:

trait Reportable {
  def getAttributes : Map[String,Any]
}

object Reportable {
  implicit class MapReportableOps(private val underlying: Map[String, Any]) extends Reportable {
    def getAttributes: Map[String, Any] = underlying
  }
}
Run Code Online (Sandbox Code Playgroud)

用法:

val reportables: List[Reportable] = Map("foo" -> "bar") :: Nil
Run Code Online (Sandbox Code Playgroud)

编译器应该在MapReportableOps任何地方找到地图的隐式包装类Reportable并创建一个Reportable.

  • 只需删除`extends AnyVal`即可. (2认同)