Reputation: 2175
I have a class that takes key value pairs, this can come in the form a of a map object or a case class for example. Lets define the following abstraction:
trait Reportable {
def getAttributes : Map[String,Any]
}
I want to have a method that takes a List[Reportable]. The possible implementations for reportable are:
The issue is i cannot figure out how to make Product (the base class of of all case classes) and the Map class implement my trait. I want to be able to take an existing class and mix in a the reportable trait, implementing it in terms of the methods the class already has.
Upvotes: 3
Views: 1361
Reputation: 7162
You cannot mix a trait in like that, I think.
However, imho, sounds like a case for the EnrichMyLibrary Pattern. Example for 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
}
}
Usage:
val reportables: List[Reportable] = Map("foo" -> "bar") :: Nil
The compiler should find the implicit wrapper class MapReportableOps
for the map wherever a Reportable
is expected and create a Reportable
.
Upvotes: 8