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

本秂侑毒 提交于 2019-12-01 07:01:37

问题


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? It sure could know that b.t is at least a String. Writing

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

works, but it is redundant with respect to the declaration of the class itself.


回答1:


First, I have edited the question title. You are not using dependent types, which Scala doesn't have anyway, but existential types. Second, you are not inferring anything, you are explicitly declaring the type.

Now, if you did write Bounded[Any], Scala wouldn't let you. 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.

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.




回答2:


There was a lengthy discussion about this topic recently on the mailing list, Type Boundary "Stickyness" on Wildcards.

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.

@extempore did find one upside to the discussion :)

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.



来源:https://stackoverflow.com/questions/4323140/why-are-the-bounds-of-type-parameters-ignored-when-using-existential-types-in-sc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!