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

Scala-null(?)作为命名Int参数的默认值,scala,parameters,null,named,Scala,Parameters,Null,Named,我想在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

我想在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);
在Scala中,我可以做到:

def recv(from: String,
         key: Int = null.asInstanceOf[Int]) {
    /* ... */
}
def recv(from: String,
         key: Option[Int] = None) {
    /* ... */
}
但它看起来很丑。或者我可以:

def recv(from: String,
         key: Int = null.asInstanceOf[Int]) {
    /* ... */
}
def recv(from: String,
         key: Option[Int] = None) {
    /* ... */
}
但现在用钥匙打电话看起来很难看:

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

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

正确的方法当然是使用
选项。如果您对它的外观有问题,您可以使用Java中的方法:使用
Java.lang.Integer
选项
方法是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。顺便说一句,安装[Int]
的计算结果为
0

选项
听起来确实是您问题的正确解决方案-您确实希望有一个“可选的”
Int

如果您担心呼叫者必须使用
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]) {
  ...
}

默认值=-1或0如何?@Antoras这是可能的,但并不优雅(假设键可以是任何Int值)。“Some”将不再难看,一旦它将您从几十个NullPointerException中解救出来:)嗯,我会把OP的
/*做一些准备工作*/
放在两个方法重载中,然后调用一个方法重载,
/*做实际工作*/
选项
的使用更惯用Scala吗?@TimGoodman,“然后调用一个方法重载”--使用什么参数?使用从
传递到两个方法重载的字符串