1
votes

I tried to create a type alias related to dependent type _ >: a.type.

The Scala compiler reports an error that I did not understand:

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]
                                 ^

If I replace a: A to a: A with AnyRef, it works:

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

Why? What is the purpose of the restriction?

1

1 Answers

5
votes

See: 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.