tags:

views:

55

answers:

1
class Test {
    import scala.collection._

    class Parent
    class Child extends Parent

    implicit val children = mutable.Map[String, Child]()

    def createEntities[T <: Parent](names: String*) = names.foreach(createEntity[T])


    def createEntity[T <: Parent](name: String)(implicit map: mutable.Map[String, T]): Unit = map.get(name) match {
        case None => println( name + " not defined.")
        case _ =>
    }
}

Why the compiler complains:

error: could not find implicit value for parameter map: scala.collection.mutable.Map[String,T] names.foreach(createEntity[T])

?

+2  A: 

If you call, e.g., createEntities[Parent]("A", "B") (which you can, because Parent is a subtype of Parent), it needs an implicit mutable.Map[String, Parent], and there isn't one. To be more precise, your definitions require you to supply a mutable.Map[String, T] for every subtype of Parent, not just those already defined:

implicit def aMap[T <: Parent]: mutable.Map[String, T] = ...
Alexey Romanov
I can not accept this answer because it compiles if change createEntities definition to : def createEntites[T<:Parent](name:String*) = {}
xiefei
It's the `names.foreach(createEntity[T])` call which requires an implicit argument. If you remove this call, of course it compiles!
Alexey Romanov
Got it. It is legal to call : createEntity[Child]() but not createEntity[T]() because there is an implicit value for mutable.Map[String, Child] but none for mutable.Map[String, T]
xiefei
Yes, precisely.
Alexey Romanov