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类实现我的特性.我希望能够获取现有的类并混合可报告的特性,并根据类已有的方法实现它.
我认为你不能混合这样的特质.
然而,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.
| 归档时间: |
|
| 查看次数: |
420 次 |
| 最近记录: |