Scala默认参数和null [英] Scala default parameters and null

查看:43
本文介绍了Scala默认参数和null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的方法:

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

如果方法如下调用,则param被赋予默认值asdf":

If the method is called as follows, then param is given the default value "asdf":

aMethod() ...

但我想要的是,如果使用 null 调用该方法,则也将应用默认值:

But what I would like, is that if the method is called with null, then the default value would also be applied:

aMethod(null)  //inside the method, I can use `param` and it has the value "asdf".

在 Scala 中执行此操作的最佳方法是什么?我可以想到模式匹配或简单的 if 语句.

Whats the best way to do this in Scala? I can think of pattern matching or a simple if statement.

推荐答案

模式匹配

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

选项(隐式)

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

选项(明确)

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.

这篇关于Scala默认参数和null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆