我想要做的就是這個代碼轉換爲斯卡拉:無法Java代碼轉換爲斯卡拉一個
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代碼。
Java代碼是錯誤的。 'float []'不是'Object []'。你的意思是'Object [] res = ...'? –
@RexKerr,對不起,我沒有看到Java代碼有什麼問題。不過,我編輯它以使其更精確。 –
@Rew Kerr:儘管它是錯誤的,但它是(可悲的)有效的java代碼,並且潛在的不一致性在運行時處理(請參見http://en.wikipedia.org/wiki/Covariance_and_contravariance_(computer_science)#Covariant_arrays_in_Java_and_C.23) 。 –