0

我在 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这里申请,但我无法意识到我将如何做到这一点。有没有办法让它在简单性和性能方面都更有效?

4

1 回答 1

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)
}
于 2013-06-22T06:09:09.273 回答