Scala Type Malfunction in 2.7: is there a workaround?

I have a problem with a parameterized class as a key type Map

. First, create a parameterized class:

scala> sealed abstract class Foo[T]{  def t: T }
defined class Foo

      

Now create some imaginary set of them using unknown parameters:

scala> var l: List[Foo[_]] = Nil
l: List[Foo[_]] = List()

      

Now create a map to save them to:

scala> var mm: Map[Foo[_], Any] = Map.empty
mm: Map[Foo[_],Any] = Map()

      

Now try to fill in the card

scala> l.foreach { foo: Foo[_] =>
     | mm += (foo -> "BAR")
     | }

      

Gives me the following compiler error:

<console>:9: error: type mismatch;  
found   : foo.type (with underlying type Foo[_])  
required: Foo[_$1] where type _$1  
       mm += (foo -> "BAR")  
              ^

      

This compiles in 2.8. Is there any workaround to get this to work in 2.7?

EDIT - this helped me too:

var mm: Map[AnyRef, Any] = Map.empty //note not Foo[_]

scala> l.foreach { foo: Foo[_] =>
     | mm += ( (foo: AnyRef) -> "BAR") //still have to tell compiler foo is an AnyRef
     | }

      

+2


source to share


1 answer


This works well for me (even in Scala 2.7):

scala> l.foreach {foo: Foo [_] =>
     | mm + = (foo.asInstanceOf [Foo [_]] -> "BAR")
     | }


Strange, but this does seem to be a bug in 2.7, which is fixed in 2.8.

+1


source







All Articles