2

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 ?

9
  • "It breaks existing calls." You mean binary incompatible, right? Also what platform are you on? JVM? Commented Jan 25, 2024 at 14:39
  • @Sweeper I mean just compile error Commented Jan 25, 2024 at 14:41
  • Oh you're right. I didn't expect this to be source incompatible. Commented Jan 25, 2024 at 14:42
  • @Sweeper me too) So I've decided to ask Commented Jan 25, 2024 at 14:44
  • 1
    Have you tried just refactoring using IntelliJ or some other IDE. Rightclick the function > Refactor > Change Signature. Here you can add new parameters and add default arguments which will be automatically inserted at every call. Commented Jan 25, 2024 at 16:38

1 Answer 1

2

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)
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.