Scala default parameters and null

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.

Leave a Comment