我在Scala中有代码:
def method1(obj: AnyRef) = {
if (obj == null) return "null"
if (obj.isInstanceOf[Array[Boolean]]) {
return Arrays.toString(obj.asInstanceOf[Array[Boolean]])
}
if (obj.isInstanceOf[Array[Char]]) {
return Arrays.toString(obj.asInstanceOf[Array[Char]])
}
if (obj.isInstanceOf[Array[Byte]]) {
return Arrays.toString(obj.asInstanceOf[Array[Byte]])
}
if (obj.isInstanceOf[Array[Long]]) {
return Arrays.toString(obj.asInstanceOf[Array[Long]])
}
// and so on....
我正在考虑在这里申请match
,但我无法意识到我会怎么做。有没有办法在简单性和性能方面提高效率?
答案 0 :(得分:1)
简单?
scala> def f(a: Any) = a match {
| case _: Array[Int] => "ints"
| case _: Array[Double] => "dubs"
| }
f: (a: Any)String
scala> f(Array(1,2,3))
res2: String = ints
scala> f(Array(1.1,2.2,3.3))
res3: String = dubs
我猜你的意思是:
def f(a: Any) = a match {
case x: Array[Int] => Arrays.toString(x)
case x: Array[Double] => Arrays.toString(x)
}