为什么 Scala 编译器禁止将通配符类型声明为类型参数的超类型
Why does Scala compiler forbid declaration of a wildcard type as super type of a type parameter
我试图创建一个与依赖类型相关的类型别名 _ >: 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 vs AnyRef
Currently there is a possibility to use singleton types in some contexts, but only on identifiers which point to a constant that conforms to AnyRef. This restriction is due to Any not having an eq method, which is what’s used for singleton type-equality check and pattern matching https://github.com/scala/scala/pull/3558. This has been discussed on the mailing list here and here, and there is a consent that this needs to be done.
我试图创建一个与依赖类型相关的类型别名 _ >: 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 vs AnyRef
Currently there is a possibility to use singleton types in some contexts, but only on identifiers which point to a constant that conforms to AnyRef. This restriction is due to Any not having an eq method, which is what’s used for singleton type-equality check and pattern matching https://github.com/scala/scala/pull/3558. This has been discussed on the mailing list here and here, and there is a consent that this needs to be done.