Can Scala select a concrete implicit when mapping a list of concrete objects inheriting a common trait? -
expanding on bit further on previous similar question posted yesterday
employee
, manager
both extend person
. i've defined implicit "converter" objects both subclasses.
i created list of type list[product serializable person]
contains 1 of each concrete class.
import scala.reflect.classtag object example { trait person { def age: int } case class employee(age: int) extends person case class manager(age: int) extends person class converter[t] { def convert(t: t) = (t,t) } def convert[t <: person:classtag](p: t)(implicit converter: converter[t]) = converter.convert(p) def main(args: array[string]): unit = { implicit val employeeconverter = new converter[employee]() implicit val managerconverter = new converter[manager]() convert(employee(1)) // works convert(manager(2)) // works list(employee(3),manager(4)) map(e => convert(e)) // compile error } }
convert
ing employee
, manager
separately works fine, when try convert
list, scala compiler complains because can't find converter
person
:
$ scalac example.scala && scala example example.scala:21: error: not find implicit value parameter converter: example.converter[product serializable example.person] list(employee(3),manager(4)) map(e => convert(e))
how can guarantee scala compiler have defined implicit conversion concrete implementations of person
?
no, cannot. have @ scala documentation http://scala-lang.org/files/archive/spec/2.11/07-implicits.html
however, if there conflicts implicits caused class hierarchy / inheritance specific 1 chosen. if manager inherited employee, should resolve fine.
similar post here, what scala's rules resolving conflicting implicit values
Comments
Post a Comment