假设我最初有功能:
fun foo(arg1: Int, vararg strings: String) {
}
还有很多这样的电话:
foo(1, "a", "b", "c")
现在我想添加带有默认值的附加参数,以避免需要更改现有调用:
我试过了
fun foo(arg1: Int, arg2: Double = 0.0, vararg strings: String) {
}
但是它破坏了现有的调用:
类型不匹配。 必需的: 双倍的 成立: 字符串
我也找到了这种方法:
fun foo(arg1: Int, vararg strings: String, arg2: Double = 0.0) {
}
它不会破坏现有的调用,但如果我想使用自定义值
arg2
我必须明确命名参数:
foo(1, "a", "b", "c", arg2 = 0.0)
因为以下调用会导致编译错误:
foo(1, "a", "b", "c", 0.0)
对于我的用例有更好的选择吗?
我只是创建一个新的重载,而不是使用具有默认值的参数。
// add this new overload
fun foo(arg1: Int, arg2: Double, vararg strings: String) {
// move the implementation to the new overload...
}
fun foo(arg1: Int, vararg strings: String) {
// the old overload will call the new overload and pass some default values
foo(arg1, 0.0, *strings)
}