简体   繁体   English

在Scala中使用存在类型时,为什么忽略类型参数的边界?

[英]Why are the bounds of type parameters ignored when using existential types in Scala?

What I mean is this: 我的意思是:

scala> class Bounded[T <: String](val t: T)
defined class Bounded

scala> val b: Bounded[_] = new Bounded("some string")
b: Bounded[_] = Bounded@2b0a141e

scala> b.t
res0: Any = some string

Why does res0 have type Any and not String? 为什么res0的类型是Any而不是String? It sure could know that bt is at least a String. 它肯定知道bt至少是一个String。 Writing 写作

val b: Bounded[_ <: String] = new Bounded("some string")

works, but it is redundant with respect to the declaration of the class itself. 有效,但对于类本身的声明而言是多余的。

First, I have edited the question title. 首先,我编辑了问题标题。 You are not using dependent types, which Scala doesn't have anyway, but existential types. 您没有使用Scala不具备的依赖类型,而是存在类型。 Second, you are not inferring anything, you are explicitly declaring the type. 其次,你没有推断任何东西,你明确地声明了这种类型。

Now, if you did write Bounded[Any] , Scala wouldn't let you. 现在,如果你写了Bounded[Any] ,Scala不会让你。 However, one of the uses of existential types is to deal with situations where the type parameter is completely unknown -- such as Java raw types, where. 但是,存在类型的一个用途是处理类型参数完全未知的情况 - 例如Java原始类型,其中。

So my guess is that making an exception in a situation that seems obvious enough will break some other situation where existential type is the only way to deal with something. 所以我的猜测是,在一个看似足够明显的情况下做一个例外会破坏其他情况,其中存在类型是处理某事的唯一方法。

There was a lengthy discussion about this topic recently on the mailing list, Type Boundary "Stickyness" on Wildcards . 最近在邮件列表上对这个主题进行了长时间的讨论, 在Wildcards上输入Type Boundary“Stickyness”

It wasn't conclusive, other than to agree that existential types, such as Bounded[_] (a shorthand for Bounded[$1] forSome { type $1 } ), don't lend themselves to intuition. 这并不是决定性的,除了同意存在主义类型,例如Bounded[_] (有Bounded[$1] forSome { type $1 }的简写),不适合直觉。

@extempore did find one upside to the discussion :) @extempore确实找到了讨论的一个好处:)

On the plus side I'm finally reading the spec cover to cover. 从好的方面来说,我终于阅读规范封面了。 I had no idea the complete lyrics to "yellow submarine" were in the specification! 我不知道“黄色潜水艇”的完整歌词在规格中! Yet I have to admit, in context it was hard to see any other way that section could have been written. 但我不得不承认,在上下文中很难看出该部分可以写成任何其他方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM