我无法理解 scala 的类型系统问题。下面的代码片段说明了这个问题。能够在可以具有 A 类型的键或 A 的子类型的类中拥有映射成员的正确方法是什么?我认为第二种方法是正确的,但是当我尝试从地图中获取元素时出现错误。这与存在类型有关吗?
sealed abstract class MyBaseType
case class Concrete1() extends MyBaseType
case class Concrete2() extends MyBaseType
case class DictVariant1(data: Map[MyBaseType, Double])
case class DictVariant2(data: Map[_ <: MyBaseType, Double])
object App {
def main(args: Array[String]) {
val d = List((Concrete1(), 3.5)).toMap
/* this fails with:
* type mismatch;
* found: scala.collection.immutable.Map[Concrete1,Double]
* required: Map[MyBaseType,Double]
* Note: Concrete1 <: MyBaseType, but trait Map is invariant in type A.
* You may wish to investigate a wildcard type such as `_ <: MyBaseType`.
* (SLS 3.2.10)
*
*/
val dv1 = DictVariant1(d)
dv1.data.get(d)
/* Works fine */
val dv2 = DictVariant2(d)
/* this fails with:
* type mismatch;
* found: d.type (with underlying type scala.collection.immutable.Map[Concrete1,Double])
* required: _$1
*
*/
dv2.data.get(Concrete1())
}
}