1

我试图创建与依赖类型_ >: a.type相关的类型别名。为什么Scala编译器禁止将通配符类型声明为类型参数的超类型

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: Aa: A with AnyRef,它的工作原理:

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

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

回答

5

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

任何VS AnyRef

目前有在某些情况下使用单种的可能性,但仅限于标识其指向符合AnyRef恒定。这个限制是由于任何没有eq方法,这是什么用于单体类型相等检查和模式匹配https://github.com/scala/scala/pull/3558。邮件列表herehere已经讨论过这个问题,并且同意这需要完成。

+0

我还是不明白它为什么会影响_>:a.type。我认为像_>:a.type这样的存在类型永远不会涉及类型相等检查。 –

+0

我假设应用保护措施时不考虑上下文;让我们希望斯卡拉语言大师之一将澄清。 – devkat