scala Scala默认参数和null
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9727401/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Scala default parameters and null
提问by John Smith
I have a method like this:
我有一个这样的方法:
def aMethod(param: String = "asdf") = {
...
}
If the method is called as follows, then param is given the default value "asdf":
如果按如下方式调用该方法,则 param 将被赋予默认值“asdf”:
aMethod() ...
But what I would like, is that if the method is called with null, then the default value would also be applied:
但我想要的是,如果使用 调用该方法null,则也将应用默认值:
aMethod(null) //inside the method, I can use `param` and it has the value "asdf".
Whats the best way to do this in Scala? I can think of pattern matching or a simple ifstatement.
在 Scala 中执行此操作的最佳方法是什么?我可以想到模式匹配或简单的if语句。
回答by Tomasz Nurkiewicz
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.
一旦你习惯了,最后一种方法实际上是最惯用和可读的。
回答by Vlad Gudim
If the method has just one or two default parameters that can be set to nullconsider this pattern:
如果该方法只有一个或两个可以设置的默认参数来null考虑这种模式:
// please note that you must specify function return type
def aMethod (x:String = "asdf"):String = if (x==null) aMethod() else {
// aMethod body ...
x
}
There are some benefits:
有一些好处:
- The method definition clearly indicates the parameter's default value.
- The correct default value can be picked by Scala tools, including ScalaDoc.
- There is no need to define an additional value to substitute for the original parameter within the method body - less room for mistakes, easier to reason.
- The pattern is fairly concise.
- 方法定义清楚地指明了参数的默认值。
- Scala 工具可以选择正确的默认值,包括 ScalaDoc。
- 无需定义额外的值来替代方法主体内的原始参数 - 出错的空间更小,更容易推理。
- 模式相当简洁。
Furthermore, consider the following scenario:
此外,请考虑以下场景:
trait ATrait {
def aMethod (x:String = "trait's default value for x"):String
}
class AClass extends ATrait {
....
}
Clearly, here we need to extend the trait, whilst preserving the original default value. Any of the patterns that involve initially setting the parameter to nullfollowed by a check and actual default value will break the contract established by the trait:
显然,这里我们需要扩展特征,同时保留原始默认值。任何涉及最初将参数设置为null后跟检查和实际默认值的模式都将破坏由 trait 建立的契约:
class AClass extends ATrait {
// wrong, breaks the expected contract
def aMethod(x: String = null):String = {
val xVal = if (x == null) "asdf" else x
...
}
}
Indeed in this scenario the only way to preserve the original value from ATraitwill be:
实际上,在这种情况下,保留原始值的唯一方法ATrait是:
class AClass extends ATrait {
override def aMethod (x:String):String = if (x==null) aMethod() else {
... // x contains default value defined within ATrait
}
}
However, in the scenario when there are more than one or two default parameters that can be set to nullthe pattern starts getting rather messy:
但是,在可以为null模式设置一两个以上默认参数的情况下,会开始变得相当混乱:
// two parameters
def aMethod (x:String = "Hello",y:String = "World"):String =
if (x==null) aMethod(y=y) else
if (y==null) aMethod(x=x) else {
// aMethod body ...
x + " " + y
}
// three parameters
def aMethod (x:String = "Hello",y:String = " ",z:String = "World"):String =
if (x==null) aMethod(y=y,z=z) else
if (y==null) aMethod(x=x,z=z) else
if (z==null) aMethod(x=x,y=y) else {
// aMethod body ...
x + y + z
}
Still when overriding an existing contract this might be the only way to honour the original default values.
仍然在覆盖现有合同时,这可能是遵守原始默认值的唯一方法。
回答by dhg
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 Optionbe possible in your case? For this you could do:
但必须问一个问题:为什么允许null?将Option你的情况可能吗?为此,您可以这样做:
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.
这清楚地表明您的方法期望“空”参数的可能性。

