繁体   English   中英

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

[英]How to match the type of an array in Scala?

给定一个接收参数arr : Array[Any]的函数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

您不能匹配整个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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM