【问题标题】:Scala how to pattern match for a None arrayScala如何对None数组进行模式匹配
【发布时间】:2013-12-15 04:28:03
【问题描述】:

对于以下方法,检查传入数组是否为 None 的方法是什么(又名 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
    ..

错误是:

<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
                 ^

【问题讨论】:

    标签: arrays scala nonetype


    【解决方案1】:

    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
    

    【讨论】:

      猜你喜欢
      • 2011-10-02
      • 2021-04-08
      • 2021-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-10
      • 2015-04-02
      相关资源
      最近更新 更多