【问题标题】:Why does the Scala compiler prefer to infer an argument of value null as Array[Char] instead of Object?为什么 Scala 编译器更喜欢将值为 null 的参数推断为 Array[Char] 而不是 Object?
【发布时间】:2011-01-15 17:03:40
【问题描述】:

考虑java.lang.String中的这些方法

/**
 * Returns the string representation of the <code>Object</code> argument.
 *
 * @param   obj   an <code>Object</code>.
 * @return  if the argument is <code>null</code>, then a string equal to
 *          <code>"null"</code>; otherwise, the value of
 *          <code>obj.toString()</code> is returned.
 * @see     java.lang.Object#toString()
 */
public static String valueOf(Object obj) {
    return (obj == null) ? "null" : obj.toString();
}

/**
 * Returns the string representation of the <code>char</code> array
 * argument. The contents of the character array are copied; subsequent
 * modification of the character array does not affect the newly
 * created string.
 *
 * @param   data   a <code>char</code> array.
 * @return  a newly allocated string representing the same sequence of
 *          characters contained in the character array argument.
 */
public static String valueOf(char data[]) {
    return new String(data);
}

还有这个 Scala 代码

val result = String.valueOf(null)

导致

String.valueOf(null)
java.lang.NullPointerException
  at java.lang.String.<init>(String.java:193)
  at java.lang.String.valueOf(String.java:2852)

如果您使用除Array[Char] 之外的任何其他类型注释null,它就会起作用。

考虑到Array 实际上是最终的并且不能被覆盖并且其元素类型是不变的,为什么 Scala 编译器似乎更喜欢 Array[Char] 而不是 Object小)?

【问题讨论】:

    标签: java scala interop null overloading


    【解决方案1】:

    Array[Char] 优于 Object,因为它更具体。如果某些东西可以转换为 X 或 Y 类型,并且存在从 X 到 Y 的转换,那么 X 比 Y 更具体......并且在重载方面 X 比 Y 更有效。

    至少,这是假设 Scala 在重载解析方面与 Java 相似,我强烈期望它是。

    这应该很容易避免 - 只需将空引用转换为 Object,以使采用 Array[Char] 的重载不适用。

    编辑:好的,看过Scala language specification 简要它比这要复杂一些,但我相信基本前提是相同的。有关所有血腥细节,请参阅上一个链接中的 p97。

    【讨论】:

    • 我假设您的意思是“可以转换为”作为“是的子类型”而不是在范围内具有隐式转换的东西?因为null 是Null 类型的值,它是任何引用类型的子类型,而Array[Char] 是Object 的子类,它只是决定数组更适合? ...我想真正的问题是这里的命名。 valueOf(char[]) 真的应该有一个不同的名字,因为它做了不同的事情。 C# 是否有同样的问题,因为它基本上复制了 Java 在过去的所有东西(并且 java.lang.String 自 JDK 1.0 以来就存在)?
    • @soc:Java 和 .NET 有相当不同的 String 类。事实上,.NET 和 Java 之间有很多不同的库,并且从 1.0 开始就存在。这些语言当然有很多相似之处,但并不像你想象的那么简单。
    • 在 Scala 术语中,“可以转换为”我的意思是“与”看起来“兼容”。来自规范:“null 值是 scala.Null 类型,因此与每个引用类型兼容。”
    猜你喜欢
    • 2015-12-04
    • 2014-08-19
    • 2017-11-03
    • 1970-01-01
    • 2019-04-20
    • 1970-01-01
    • 1970-01-01
    • 2015-08-13
    • 1970-01-01
    相关资源
    最近更新 更多