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

发布于 2024-10-05 04:43:48 字数 417 浏览 4 评论 0原文

我的意思是:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

寂寞陪衬 2024-10-12 04:43:48

首先,我编辑了问题标题。您没有使用依赖类型(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.

Hello爱情风 2024-10-12 04:43:48

最近在邮件列表上对此主题进行了长时间的讨论,在通配符上键入边界“粘性”。

这不是结论性的,只是同意存在类型,例如 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 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文