Answering my own question, as recommended by recommendations .
What you can do is declare the parameters in the calling functions as nullable and use null as the default argument:
fun foo2(bar: String? = null: Int? = null) { // do stuff foo(bar, baz) } fun foo3(bar: String? = null, baz: Int? = null) { // do other stuff foo(bar, baz) }
Then use one of the elvis operator to use the default values ββwhen null provided.
fun foo(bar: String? = null, baz: Int? = null) { val realBar = bar ?: "ABC" val realBaz = baz ?: 42 }
If you are dealing with a class instead of a function, you can pull out the constructor property and assign it a default value:
class Foo(bar: String? = null, baz: Int? = null) { val bar = bar ?: "ABC" val baz = baz ?: 42 }
Alternatively, say if your class is a data class and you want to have properties in the main constructor, you can declare a factory method to handle the default values:
class Foo(val bar: String, baz: Int) { companion object { fun create(bar: String? = null, baz: Int? = null) = Foo(bar ?: "ABC", baz ?: 42) } }
source share