为什么Scala编译器更喜欢将值为null的参数推断为Array [Char]而不是Object?

soc*_*soc 1 java null interop scala overloading

考虑这些方法 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);
}
Run Code Online (Sandbox Code Playgroud)

和这个Scala代码

val result = String.valueOf(null)
Run Code Online (Sandbox Code Playgroud)

结果

String.valueOf(null)
java.lang.NullPointerException
  at java.lang.String.<init>(String.java:193)
  at java.lang.String.valueOf(String.java:2852)
Run Code Online (Sandbox Code Playgroud)

如果您使用null除以外的任何其他类型进行注释,它将起作用Array[Char].

为什么Scala编译器似乎更喜欢Array[Char]Object考虑Array是有效的最终的,不能被覆盖,并在其元素类型不变(使这种用法意的机会是非常小的)?

Jon*_*eet 5

Array[Char]比较喜欢,Object因为它更具体.如果某些东西可以转换为X或Y类型,并且有从X Y 的转换,那么X比Y更具体......当涉及到重载时,X实际上优于Y.

至少,假设Scala在重载分辨率方面就像Java一样,我强烈期望它.

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

编辑:好的,简单地看一下Scala语言规范 它比这复杂一点,但我相信基本前提是一样的.有关所有血腥细节,请参见上一链接中的p97.