【发布时间】: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