gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 09:32:37 30 4
gpt4 key购买 nike

我想在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方法是什么?谢谢你。

最佳答案

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

关于Scala-空(?)作为命名Int参数的默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8972466/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com