8

我想在 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) {
    /* ... */
}

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

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

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

4

3 回答 3

17

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]顺便0说一下。

于 2012-01-23T14:01:48.017 回答
3

Option听起来确实是解决您问题的正确方法-您确实确实想要一个“可选” 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]) {
  ...
}
于 2012-01-23T14:02:00.957 回答
2

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

于 2012-01-23T14:00:19.187 回答