Kotlin has default arguments for function and constructor parameters. Now, I have a function
fun foo(bar: String = "ABC", baz: Int = 42) {}
and I want to call it from different places but also retain the possibility to not pass on of the arguments and instead use the default value.
I know, I can declare the default arguments in the calling functions
fun foo2(bar: String = "ABC", baz: Int = 42) {
// do stuff
foo(bar, baz)
}
fun foo3(bar: String = "ABC", baz: Int = 42) {
// do other stuff
foo(bar, baz)
}
but now my default parameter in foo
is pointless as it's always overwriten and I have duplicated the default arguments in all calling functions. That's not very DRY.
Is there a better way to propagate the default arguments?
Instead of having three functions with the same default arguments:
fun foo(bar: String = "ABC", baz: Int = 42)
fun foo2(bar: String = "ABC", baz: Int = 42)
fun foo3(bar: String = "ABC", baz: Int = 42)
Create a wrapper class that takes in the arguments, and have the functions without parameters:
class Foo(val bar: String = "ABC", val baz: Int = 42) {
fun foo() { /* ... */ }
fun foo2() {
// ...
foo()
}
fun foo3() {
// ...
foo()
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With