Scala default parameters and null

前端 未结 3 2107
無奈伤痛
無奈伤痛 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:13

    Pattern matching

    def aMethod(param: String = null) {
        val paramOrDefault = param match {
            case null => "asdf"
            case s => s
        }
    }
    

    Option (implicitly)

    def aMethod(param: String = null) {
        val paramOrDefault = Option(param).getOrElse("asdf")
    }
    

    Option (explicitly)

    def aMethod(param: Option[String] = None) {
        val paramOrDefault = param getOrElse "asdf"
    }
    

    The last approach is actually the most idiomatic and readable once you get use to it.

提交回复
热议问题