Scala default parameters and null

前端 未结 3 2115
無奈伤痛
無奈伤痛 2020-12-24 06:09

I have a method like this:

def aMethod(param: String = \"asdf\") = {
    ...
}

If the method is called as follows, then param is given the

3条回答
  •  忘掉有多难
    2020-12-24 07:06

    def aMethod(param: String = null) = { 
      val p = 
        if(param == null)
          "asdf"
         else
           param
    
      println(p) 
    }
    

    But the question must be asked: why allow null? Would Option be possible in your case? For this you could do:

    def aMethod(param: Option[String]) = { 
      val p = param.getOrElse("asdf")    
      println(p)
    }
    

    This makes it clear that your method expects the possibility of a "null" argument.

提交回复
热议问题