我有一个接受键值对的类,它可以以map对象或case类的形式出现。让我们定义以下抽象:
trait Reportable { def getAttributes : Map[String,Any] }
可报告的可能实现包括:
问题是我不知道如何使Product(所有case类的基类)和Map类实现我的特性。我希望能够接受一个现有的类,并将其混合到可报告特性中,根据该类已有的方法实现它。
我认为,你不能把一种特质混为一谈。
然而,imho听起来像是 EnrichMyLibrary公司 图案示例 Map :
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 } }
用法:
val reportables: List[Reportable] = Map("foo" -> "bar") :: Nil
MapReportableOps 对于地图 Reportable 并创建一个 可报告 .
MapReportableOps
Reportable
可报告