这段代码是可行的:
这个不行:
语言规范说明:
scala> val x = ""
x: java.lang.String = ""
scala> Tuple2[x.type, x.type](x,x)
res5: (x.type, x.type) = ("","")
这个不行:
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)
^
除此之外,还有这个:
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)
^
语言规范说明:
这个限制的背后有什么理由?最近类似于单例类型的形式为 p.type,其中 p 是指向预期符合 scala.AnyRef (§6.1)的值的路径。
0.getClass
的限制是否有意义?