【问题标题】:Why does the explicit syntax for creating Tuples only allow AnyRefs as type annotations?为什么创建元组的显式语法只允许 AnyRefs 作为类型注释?
【发布时间】:2011-10-04 17:00:01
【问题描述】:

此代码有效:

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 上发生的那样解除限制是否有意义?

【问题讨论】:

  • 如您的示例所示,它与元组绝对无关。关键是您不能对值类型执行 .type 。我不知道这是否可行,并想知道它什么时候有用。
  • 这不是我引用的内容(第 6.1 节)并且想知道其背后的基本原理是什么?
  • 确实你的问题就这样结束了。然而,标题(和你的例子)提到了元组。
  • 由于 JVM 上有类型擦除,我根本不建议使用 .type。如果您想灵活处理类型,请使用泛型。

标签: scala types singleton tuples


【解决方案1】:

正如您在 Scala class hierarchyIntUnitBoolean(和其他)上看到的那样,它们不是 AnyRef 的子类,因为它们被翻译成 java intvoidboolean 和以此类推,witch 不是Object 的子类。

【讨论】:

  • 但是为什么会有这个限制呢?
猜你喜欢
  • 2020-04-22
  • 2011-11-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-03
相关资源
最近更新 更多