我想做的是将此代码转换为Scala:
Object[] method1(Object obj) {
if (obj instanceof int[]) {
int sourceArr[] = (int[]) obj;
Integer[] res = new Integer[sourceArr.length];
for (int i = 0; i < sourceArr.length; i++)
res[i] = sourceArr[i];
return res;
}
else if // and so on for double, int, boolean ...
else if (obj instanceof Object[]) {
return (Object[]) obj;
} else {
return new Object[] { obj };
}
}
这是我的尝试:
def method1(obj: Any): Array[Any] = obj match {
case x: Array[AnyRef] => x
case x: Array[Int] => x
// and so on for Double, Boolean, Char, Byte, Long....
case _ => new Array[Any]()
}
和错误:
1) overloaded method constructor Array with alternatives:
[error] (dim1: Int,dim2: Int,dim3: Int,dim4: Int,dim5: Int,dim6: Int,dim7: Int,dim8: Int,dim9: Int)Array[Any] <and>
[error] (dim1: Int,dim2: Int,dim3: Int,dim4: Int,dim5: Int,dim6: Int,dim7: Int,dim8: Int)Array[Any] <and>
[error] (dim1: Int,dim2: Int,dim3: Int,dim4: Int,dim5: Int,dim6: Int,dim7: Int)Array[Any] <and>
[error] (dim1: Int,dim2: Int,dim3: Int,dim4: Int,dim5: Int,dim6: Int)Array[Any] <and>
[error] (dim1: Int,dim2: Int,dim3: Int,dim4: Int,dim5: Int)Array[Any] <and>
[error] (dim1: Int,dim2: Int,dim3: Int,dim4: Int)Array[Any] <and>
[error] (dim1: Int,dim2: Int,dim3: Int)Array[Any] <and>
[error] (dim1: Int,dim2: Int)Array[Any] <and>
[error] (_length: Int)Array[Any]
[error] cannot be applied to ()
[error] case _ => new Array[Any]()
2) type mismatch;
[error] found : Array[Short]
[error] required: Array[Any]
[error] Note: Short <: Any, but class Array is invariant in type T.
[error] You may wish to investigate a wildcard type such as `_ <: Any`. (SLS 3.2.10)
[error] case x: Array[Short] => x
3) type mismatch;
[error] found : Array[Long]
[error] required: Array[Any]
[error] Note: Long <: Any, but class Array is invariant in type T.
[error] You may wish to investigate a wildcard type such as `_ <: Any`. (SLS 3.2.10)
[error] case x: Array[Long] => x
// and so on for each type I have -- Double, Boolean, Char, Byte, Long....
我该如何解决这个问题?在 Scala 中有没有更合理的方法来做到这一点?请注意,我无法更改 Java 代码。