首页 > 解决方案 > 如何匹配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

标签: scala

解决方案


您无法匹配整体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在不依次检查每个元素的情况下转换为另一种类型。


推荐阅读