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

发布于 2024-12-28 14:31:27 字数 677 浏览 2 评论 0原文

我想在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

满意归宿 2025-01-04 14:31:28

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

The Option way is the Scala way. You can make the user code a little nicer by providing helper methods.

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] evaluates to 0 by the way.

尬尬 2025-01-04 14:31:28

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]) {
  ...
}

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:

def recv(from: String) {
  recv(from, None)
}

def recv(from: String, key: Int) {
  recv(from, Some(key))
}

def recv(from: String, key: Option[Int]) {
  ...
}
分分钟 2025-01-04 14:31:28

正确的方法当然是使用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: use java.lang.Integer.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文