在Scala中使用存在性类型时,为什么会忽略类型参数的界限? [英] Why are the bounds of type parameters ignored when using existential types in Scala?

查看:85
本文介绍了在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?它肯定知道b.t至少是一个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.

推荐答案

首先,我编辑了问题标题.您使用的不是依存类型,Scala并没有依存类型,而是 existential 类型.其次,您没有推断任何内容,而是在明确声明类型.

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.

现在,如果您确实编写了Bounded[Any],Scala不会允许您.但是,存在类型的用途之一是处理类型参数完全未知的情况,例如Java原始类型where.

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.

这篇关于在Scala中使用存在性类型时,为什么会忽略类型参数的界限?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆