对于下面的方法,检查传入数组是否为None的方法是什么(对于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
..
错误是:
<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
^
答案 0 :(得分:5)
null
不等于None
。您应该将数组包装在Option
:
Option(arr) match {
case Some(a) => ...
case None => ...
}
Option(null)
返回None
更完整的样本:
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