此代码有效:
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是指向的路径
预期符合(第6.1节)scala.AnyRef的值。
这背后的理由是什么,并且像
0.getClass
最近发生的那样取消这种限制是否有意义? 最佳答案
如您在Scala class hierarchy Int
上看到的,Unit
,Boolean
(和其他)不是AnyRef的子类,因为它们被翻译成java int
,void
,boolean
等,巫婆不是Object
的子类。
关于scala - 为什么创建元组的显式语法仅允许AnyRef作为类型注释?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6682979/