Scala - null (?) 作为命名 Int 参数的默认值
我想在 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) {
/* ... */
}
但现在用 key 调用看起来很难看:
// case 2
recv("/x/y/z", Some(1));
什么是正确的 Scala 方式?谢谢。
I'd like to do in Scala something I would do in Java like this:
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:
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Option
方式是 Scala 方式。您可以通过提供辅助方法来使用户代码变得更好一些。顺便说一句,
null.asInstanceOf[Int]
的计算结果为0
。The
Option
way is the Scala way. You can make the user code a little nicer by providing helper methods.null.asInstanceOf[Int]
evaluates to0
by the way.Option
听起来确实是解决您问题的正确方法 - 您确实想要一个“可选”Int
。如果您担心调用者必须使用
Some
,为什么不:Option
really does sound like the right solution to your problem - you really do want to have an "optional"Int
.If you're worried about callers having to use
Some
, why not:正确的方法当然是使用
Option
。如果您对它的外观有疑问,您可以随时求助于您在 Java 中所做的事情:使用java.lang.Integer
。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: usejava.lang.Integer
.