3

This code works:

scala> val x = ""
x: java.lang.String = ""

scala> Tuple2[x.type, x.type](x,x)
res5: (x.type, x.type) = ("","")

This one doesn't:

scala> val y = 0
y: Int = 0

scala> Tuple2[y.type, y.type](y,y)
<console>:9: error: type mismatch;
 found   : y.type (with underlying type Int)
 required: AnyRef
Note: an implicit exists from scala.Int => java.lang.Integer, but
methods inherited from Object are rendered ambiguous.  This is to avoid
a blanket implicit which would convert any scala.Int to any AnyRef.
You may wish to use a type ascription: `x: java.lang.Integer`.
              Tuple2[y.type, y.type](y,y)
                     ^

As well as this one:

scala> val z = ()
z: Unit = ()

scala> Tuple2[z.type, z.type](z,z)
<console>:9: error: type mismatch;
 found   : z.type (with underlying type Unit)
 required: AnyRef
Note: Unit is not implicitly converted to AnyRef.  You can safely
pattern match `x: AnyRef` or cast `x.asInstanceOf[AnyRef]` to do so.
              Tuple2[z.type, z.type](z,z)
                     ^

The language specification says

A singleton type is of the form p.type, where p is a path pointing to a value expected to conform (§6.1) to scala.AnyRef.

What's the rationale behind that and would it make sense to lift that restriction like it recently happened with 0.getClass?

soc
  • 27,983
  • 20
  • 111
  • 215
  • As shown by your example, it has absolutely nothing to do with tuple. The point is that you cannot do .type on a value type. I don't know whether that would be feasible, and wonder when it could be useful. – Didier Dupont Jul 25 '11 at 13:34
  • Isn't that pretty much what I cited (§6.1) and wondered what's the rationale behind it? – soc Jul 25 '11 at 19:07
  • Indeed your question ends so. The title (and your example) mentions tuple however. – Didier Dupont Jul 25 '11 at 19:47
  • since there is type erasure on the JVM I wouldn't recomment to use .type at all. Use generics if you want to be flexible with types. – Arne Jul 31 '11 at 14:03

1 Answers1

0

As you can see on Scala class hierarchy Int, Unit, Boolean (and others) are not subclasses of AnyRef, because they are translated into java int, void, boolean and so on, witch are not subclasses of Object.

Keros
  • 363
  • 1
  • 11