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

wok*_*oky 7 parameters null scala 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/y/z", 1);
Run Code Online (Sandbox Code Playgroud)

在Scala我能做到:

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

但它看起来很难看.或者我可以这样做:

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

但现在用钥匙看起来很难看:

// case 2
recv("/x/y/z", Some(1));
Run Code Online (Sandbox Code Playgroud)

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

mis*_*tor 15

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)
}
Run Code Online (Sandbox Code Playgroud)

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