Yan*_* Bo 1 scala existential-type type-parameter type-bounds dependent-type
我试图创建一个与依赖类型相关的类型别名_ >: 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]
^
Run Code Online (Sandbox Code Playgroud)
如果我替换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
Run Code Online (Sandbox Code Playgroud)
为什么?限制的目的是什么?
请参阅:http://docs.scala-lang.org/sips/pending/42.type.html
任何vs AnyRef
目前,有可能在某些上下文中使用单例类型,但仅限于指向符合AnyRef的常量的标识符.这种限制是由于任何没有eq方法,这是用于单例类型相等检查和模式匹配https://github.com/scala/scala/pull/3558.这已在此处和此处的邮件列表中进行了讨论,并且已经同意这需要完成.