如何在Scala中匹配数组的类型?

时间:2019-02-08 00:20:16

标签: scala

给出一个接收参数arr : Array[Any]的函数,如何在模式中匹配Any的类型?另外,重要的是,如何同时匹配多个案例?

目前我有

def matchType (arr: Array[Any]) = {

    arr match {
        case a @ ( _: Array[Int] | _: Array[Long] | _: Array[Double] ) => arr.map(*...*);
        case b: Array[Byte] => print("byte")
        case _ => print("unknown")
    }        

}

无法编译

cmd8.sc:4: scrutinee is incompatible with pattern type;
 found   : Array[Int]
 required: Array[Any]
Note: Int <: Any, but class Array is invariant in type T.
You may wish to investigate a wildcard type such as `_ <: Any`. (SLS 3.2.10)
            case a @ ( _: Array[Int] | _: Array[Long] | _: Array[Double] ) => print("numerical");
                          ^
cmd8.sc:4: scrutinee is incompatible with pattern type;
 found   : Array[Long]
 required: Array[Any]
Note: Long <: Any, but class Array is invariant in type T.
You may wish to investigate a wildcard type such as `_ <: Any`. (SLS 3.2.10)
            case a @ ( _: Array[Int] | _: Array[Long] | _: Array[Double] ) => print("numerical");
                                          ^
cmd8.sc:4: scrutinee is incompatible with pattern type;
 found   : Array[Double]
 required: Array[Any]
Note: Double <: Any, but class Array is invariant in type T.
You may wish to investigate a wildcard type such as `_ <: Any`. (SLS 3.2.10)
            case a @ ( _: Array[Int] | _: Array[Long] | _: Array[Double] ) => print("numerical");
                                                           ^
cmd8.sc:5: scrutinee is incompatible with pattern type;
 found   : Array[Byte]
 required: Array[Any]
Note: Byte <: Any, but class Array is invariant in type T.
You may wish to investigate a wildcard type such as `_ <: Any`. (SLS 3.2.10)
            case b: Array[Byte] => print("byte")
                    ^
Compilation Failed

1 个答案:

答案 0 :(得分:1)

您不能匹配整个Array,但可以依次匹配每个元素:

def matchType (arr: Array[_]) =
  arr.foreach{
    case _: Double | _: Float => println("floating")
    case i: Int => println("int")
    case b: Byte => println("byte")
    case _ => println("other")
  }

由于Array[Any]可能包含基础类型的混合,因此如果不依次检查每个元素,就无法转换为另一类型的Array