我试图创建一个与依赖类型_ >: 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
为什么?限制的目的是什么?
请参阅:http://docs.scala-lang.org/sips/pending/42.type.html
Any与AnyRef
目前,在某些上下文中可以使用singleton类型,但只能在指向符合AnyRef的常量的标识符上使用。这个限制是由于Any没有eq方法,该方法用于singleton类型相等性检查和模式匹配https://github.com/scala/scala/pull/3558.这已经在这里和这里的邮件列表中讨论过了,并且同意需要这样做。