Scala - null (?) 作为命名 Int 参数的默认值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8972466/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 03:49:10  来源:igfitidea点击:

Scala - null (?) as default value for named Int parameter

scalaparametersnullnamed

提问by woky

I'd like to do in Scala something I would do in Java like this:

我想在 Scala 中做一些我会在 Java 中做的事情:

public void recv(String from) {
    recv(from, null);
}
public void recv(String from, Integer key) {
    /* if key defined do some preliminary work */
    /* do real work */
}

// case 1
recv("/x/y/z");
// case 2
recv("/x/y/z", 1);

In Scala I could do:

在 Scala 中,我可以这样做:

def recv(from: String,
         key: Int = null.asInstanceOf[Int]) {
    /* ... */
}

but it looks ugly. Or I could do:

但它看起来很丑。或者我可以这样做:

def recv(from: String,
         key: Option[Int] = None) {
    /* ... */
}

but now call with key looks ugly:

但现在用键调用看起来很难看:

// case 2
recv("/x/y/z", Some(1));

What's the proper Scala way? Thank you.

什么是正确的Scala 方式?谢谢你。

回答by missingfaktor

The Optionway is the Scala way. You can make the user code a little nicer by providing helper methods.

Option方法是Scala的方式。您可以通过提供辅助方法使用户代码更好一些。

private def recv(from: String, key: Option[Int]) {
  /* ... */
}

def recv(from: String, key: Int) {
  recv(from, Some(key))
}

def recv(from: String) {
  recv(from, None)
}

null.asInstanceOf[Int]evaluates to 0by the way.

null.asInstanceOf[Int]0顺便评价一下。

回答by Paul Butcher

Optionreally does sound like the right solution to your problem - you really do want to have an "optional" Int.

Option听起来确实是您问题的正确解决方案-您确实想要一个“可选” Int

If you're worried about callers having to use Some, why not:

如果您担心呼叫者必须使用Some,为什么不:

def recv(from: String) {
  recv(from, None)
}

def recv(from: String, key: Int) {
  recv(from, Some(key))
}

def recv(from: String, key: Option[Int]) {
  ...
}

回答by Daniel C. Sobral

The proper way is, of course, to use Option. If you have problems with how it looks, you can always resort to what you did in Java: use java.lang.Integer.

正确的方法当然是使用Option. 如果您对它的外观有疑问,您可以随时求助于您在 Java 中所做的:使用java.lang.Integer.