开发者

Scala Type Failure in 2.7: is there a workaround?

开发者 https://www.devze.com 2022-12-26 18:52 出处:网络
I have a problem using a parameterized class as the key-type of a Map. First create the parameterized class:

I have a problem using a parameterized class as the key-type of a Map. First create the parameterized class:

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

Now create some imaginary collection of these across unknown parameters:

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

Now create a Map to store these in:

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

Now attempt to populate the Map

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 just fine in 2.8. Is there any workaround to get this to work in 2.7?

EDIT - this also worked for me:

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 开发者_如何学PythonAnyRef
     | }


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

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

Weird, but this really seems to be a bug in 2.7 which has been fixed in 2.8.

0

精彩评论

暂无评论...
验证码 换一张
取 消