arrays - Scala 如何为 None 数组进行模式匹配

标签 arrays scala nonetype

对于下面的方法,检查传入数组是否为 None(在 Java 领域也称为 null..)的方法是什么

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
                 ^

最佳答案

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

关于arrays - Scala 如何为 None 数组进行模式匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20277897/

相关文章:

c - 更新终端上显示的文本

c# - 有没有办法将数组的不连续子集作为单个数组公开?

scala - 如何在Scala中实现具有多个最大值的maxBy

scala - 写入错误代码及其字符串消息 : Scala

django - 'NoneType' 类型的对象在 django ClassBased ListView 中没有 len()

来自mysql结果的php多维数组

arrays - Swift [String] 不可转换为 'String'

json - Play Framework Scala 格式的大型 JSON(未找到 unapply 或 unapplySeq 函数)

python - 如何计算列表中 `None` 的出现次数?

python - TypeError: 'NoneType' 类型的参数在 if 语句后不可迭代