How to add new argument with default value to function which accepts varargs in Kotlin?

75 Views Asked by At

Let's say initially I have function:

fun foo(arg1: Int, vararg strings: String) {
}

and there are a lot of calls like this:

foo(1, "a", "b", "c")

Now I want to add additional argument with default value to avoid need changing existing calls:

I tried

fun foo(arg1: Int, arg2: Double = 0.0, vararg strings: String) {
}

But it breaks existing calls:

Type mismatch. Required: Double Found: String

Also I've found this way:

fun foo(arg1: Int, vararg strings: String, arg2: Double = 0.0) {
}

It doesn't break existing calls but if I want to use custom value for arg2 I have to name argument explicitly:

foo(1, "a", "b", "c", arg2 = 0.0)

because following call leads to compile error:

foo(1, "a", "b", "c", 0.0)

Is there better option for my use case ?

1

There are 1 best solutions below

0
Sweeper On BEST ANSWER

I would just create a new overload, instead of using parameters with default values.

// 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)
}