Here is a reduced example of what I want to do. The line commented out doesn’t compile.
class Animal
object Animal { implicit def toElephant(a: Animal) = a.asInstanceOf[Elephant] }
class Elephant extends Animal
object Main {
def main(args: Array[String]) = {
val a: List[Animal] = List(new Elephant, new Elephant)
// val e: List[Elephant] = a
}
}
In a regular situation, e = a is of course illegal. But with the implicit function, one could think that scala would automatically convert every element in the list.
Is there an elegant way to get this behaviour? If yes, how?
What I wish to know is if there is some obscure corner of scala that can force the behaviour I wish. I am not interested in solutions that add cruft. I can think of them myself. For instance, one could do:
object Animal {
implicit def toElephant(a: Animal) = a.asInstanceOf[Elephant]
implicit def toElephant(a: List[Animal]) = a.asInstanceOf[List[Elephant]] }
and the code above would work.
You can forget implicits and mapping and use simply
BUT, if you insist, you can of course also do this conversion implicitly. Having an implicit from
List[A]toList[B]is no more crufty than an implicit A => B. I wouldn’t do this, but if I did I’d generalise it for re-use, importing locally to limit the implicit’s scope:Then at use-site
Be aware of the scope of the import, and stick things within a
locallyblock if necessary.