scala - Scala 中存在类型的下划线

标签 scala existential-type

我读过一篇关于 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}

他的解释。 “第三个是所有 map 类型的父类(super class)型,因此有一些 T 使得它们是 Map[Class[T], String]。所以,我们再次为 map 中的键提供了一些固定的类类型 - 它是只是这次我们不知道它是什么类型。然而,中间的键是 Class[T] forSome { type T } 类型的键。也就是说,它的键是允许具有他们想要的任何值的类类型参数。所以这就是我们真正想要的。”

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

该博客还提到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.


帖子提到这可能会在 future 改变,而且它已经改变了。现在它相当于第二个。请参阅 Scala Specification 中的此示例:

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


当我们将 _ 用于存在类型时,这会影响语义吗?

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

关于scala - Scala 中存在类型的下划线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32447779/

相关文章:

scala - 使用 Makefile 管理 Scala 项目

scala - 为什么 Scala 2.11 编译器重命名我的私有(private)方法?

scala - 编译 JavaScript 并仅在生产模式下激活的自定义 sbt 任务

java - 如何使用 Scala 中的 Enum.valueOf?

scala - scala.language.existentials 的 scaladoc 在哪里?

amazon-web-services - Hadoop s3 配置文件丢失

java - 加特林验证解码的 JWT token

scala - 存在类型表达式的Skolemization

haskell - 解构存在类型

Scala 存在性 - 类型不匹配,无法推断 T = := T