Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to propagate default arguments between functions in Kotlin?

Tags:

kotlin

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?

like image 638
Kirill Rakhman Avatar asked Nov 21 '16 12:11

Kirill Rakhman


1 Answers

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()
  }
}
like image 186
nhaarman Avatar answered Jan 03 '23 16:01

nhaarman