Scala 中存在类型的下划线

Underscore for existential type in Scala

我读过一篇关于 Scala 中存在类型的博客:Existential types in Scala

在这篇博客中,提到了一个例子:

Map[Class[T forSome { type T}], String]
Map[Class[T] forSome { type T}, String]
Map[Class[T], String] forSome { type T}

他的解释。 "the third one is the supertype of all map types such that there is some T such that they are a Map[Class[T], String]. So again, we've got some fixed class type for keys in the map - it's just that this time we don't know what type it is. The middle one however has keys of type Class[T] forSome { type T }. That is, its keys are classes which are allowed to have any value they want for their type parameter. So this is what we actually wanted."

解释不太容易理解。代码示例中的第二个和第三个有什么区别?谁能给我们举一些例子吗?

博客还提到 Map[Class[_], String] 相当于示例中的第三个,而我们实际上想要第二个。当我们使用 _ 作为存在类型时,这会影响语义吗?

What are the differences between the second and third one in the code example?

在第三种类型中,您不能有两个类型为 Class[T]T 不同的键,例如Map(classOf[Object] -> "Object", classOf[String] -> "String") 没有这种类型(但它有第二种类型)。

The blog also mention that Map[Class[_], String] is equivalent to the third one in the example, when we actually want the second one.

post 提到这可能会在未来改变,它已经改变了。现在它相当于第二个。请参阅 Scala Specification 中的示例:

The type List[List[_]] is equivalent to the existential type List[List[t] forSome { type t }].

当我们使用 _ 作为存在类型时,这会影响语义吗?

这取决于您在具体情况下想要什么。使用 _ 如果它给出了你想要的类型(根据上面链接的规范)并且你认为它比 forSome 形式更具可读性;否则使用 forSome