为什么Scala编译器禁止声明通配符类型为类型参数的超类型

时间:2016-08-03 06:24:01

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

我尝试创建与依赖类型_ >: 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

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

1 个答案:

答案 0 :(得分:5)

请参阅:http://docs.scala-lang.org/sips/pending/42.type.html

  

Any vs AnyRef

     

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

相关问题