为什么在 Scala 中使用存在类型时会忽略类型参数的边界?
我的意思是:
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
为什么 res0 的类型为 Any 而不是 String?它肯定可以知道 bt 至少是一个字符串。编写
val b: Bounded[_ <: String] = new Bounded("some string")
是可行的,但对于类本身的声明来说是多余的。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先,我编辑了问题标题。您没有使用依赖类型(Scala 没有这种类型),而是使用存在类型。其次,您没有推断任何内容,而是显式声明了类型。
现在,如果您确实编写了
Bounded[Any]
,Scala 不会允许您这样做。然而,存在类型的用途之一是处理类型参数完全未知的情况——例如 Java 原始类型,where。所以我的猜测是,在看起来足够明显的情况下破例会打破其他一些情况,其中存在类型是处理某些事情的唯一方法。
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.
最近在邮件列表上对此主题进行了长时间的讨论,在通配符上键入边界“粘性”。
这不是结论性的,只是同意存在类型,例如
Bounded[_]
(Bounded[$1] forSome { type $1 }
的简写),不不要依赖直觉。@extempore 确实发现了讨论的一个好处:)
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 forBounded[$1] forSome { type $1 }
), don't lend themselves to intuition.@extempore did find one upside to the discussion :)