【问题标题】:Why does Scala compiler forbid declaration of a wildcard type as super type of a type parameter为什么Scala编译器禁止将通配符类型声明为类型参数的超类型
【发布时间】:2016-08-03 06:24:01
【问题描述】:

我试图创建一个与依赖类型_ >: a.type相关的类型别名。

Scala编译器报错,我没看懂:

scala> def foo[A](a: A) = {
     |   type F = Function1[_ >: a.type, Unit]
     | } 
<console>:12: error: type mismatch;
 found   : a.type (with underlying type A)
 required: AnyRef
Note that A is unbounded, which means AnyRef is not a known parent.
Such types can participate in value classes, but instances
cannot appear in singleton types or in reference comparisons.
         type F = Function1[_ >: a.type, Unit]
                                 ^

如果我将a: A 替换为a: A with AnyRef,它会起作用:

scala> def foo[A](a: A with AnyRef) = {
     |   type F = Function1[_ >: a.type, Unit]
     | } 
foo: [A](a: A with AnyRef)Unit

为什么? 限制的目的是什么?

【问题讨论】:

    标签: scala type-parameter dependent-type existential-type type-bounds


    【解决方案1】:

    见:http://docs.scala-lang.org/sips/pending/42.type.html

    Any vs AnyRef

    目前有可能在某些上下文中使用单例类型,但仅限于指向符合 AnyRef 的常量的标识符。这个限制是由于 Any 没有 eq 方法,这是用于单例类型相等检查和模式匹配https://github.com/scala/scala/pull/3558。这已在邮件列表herehere 上进行了讨论,并且同意需要这样做。

    【讨论】:

    • 我还是不明白为什么会影响_>:a.type。我认为像 _ >: a.type 这样的存在类型永远不会参与类型相等检查。
    • 我假设应用保护措施时不考虑上下文;让我们希望 Scala 语言大师之一能澄清一下。
    猜你喜欢
    • 1970-01-01
    • 2012-02-17
    • 2019-06-07
    • 1970-01-01
    • 2016-07-03
    • 1970-01-01
    • 2012-04-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多