簡體   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