我想在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方式?谢谢。
答案 0 :(得分: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)
}
null.asInstanceOf[Int]
顺便评估为0
。
答案 1 :(得分: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]) {
...
}
答案 2 :(得分:2)
当然,正确的方法是使用Option
。如果您看起来有问题,可以随时使用Java中的内容:使用java.lang.Integer
。