For the following method, what is the way to check if the incoming array is None (aka null fro java land..)

val x = Array(22.0,122,222,322,422,522,622,722,822,922)
def stddev(arr :Array[Double]) =  {
    arr match {
    case  None  => 0
    ..

The error is:

<console>:11: error: pattern type is incompatible with expected type;
 found   : None.type
 required: Array[Double]
Note: if you intended to match against the class, try `case _: <none>`
           case  None  => 0
                 ^
有帮助吗?

解决方案

null isn't equals to None. You should wrap your array in Option:

Option(arr) match {
  case Some(a) => ...
  case None => ...
}

Option(null) returns None

More complete sample:

def printDoubles(arr: Array[Double]) {
    Option(arr) match {
        case Some(Array()) => println("empty array")
        case Some(a) => println(a mkString ", ")
        case None => println("array is null")
    }
}

printDoubles(null) // array is null
printDoubles(Array.empty) // empty array
printDoubles(Array(1.0, 1.1, 1.2)) // 1.0, 1.1, 1.2
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top