简体   繁体   中英

How to match the type of an array in Scala?

Given a function that receives a parameter arr : Array[Any] , how can I match the type of Any in a pattern? More, importantly, how can I match multiple cases at the same time?

Currently I have

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")
    }        

}

which fails to compile with

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

You cannot match the whole Array but you can match each element in turn:

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

Since Array[Any] could have a mixture of underlying types you can't convert to an Array of another type without checking each element in turn.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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