Search code examples
kotlindefault-parameters

Type signature for Kotlin function with default parameters


Let's say I have:

fun addInvoker(adder: () -> Int = ::add): Int{
    return adder()
}

fun add(num1:Int = 1, num2:Int = 1): Int{
    return num1 + num2
}

I get an error since ::add has two parameters, but the signature of addInvoker requires it to have zero parameters. However, if I change it to:

fun addInvoker(adder: (Int, Int) -> Int = ::add): Int{
    return adder()
}

fun add(num1:Int = 1, num2:Int = 1): Int{
    return num1 + num2
}

Then I can't invoke adder(), i.e. invoking add with its default arguments.

So, is there some way I can make ::add the default argument to invokeAdder but still invoke add with adder(), thus invoking it with the default args?


Solution

  • You can make a lambda of your add which will be no-argument function and will call add with its default arguments: { add() }.

    Complete code:

    fun addInvoker(adder: () -> Int = { add() }): Int {
        return adder()
    }
    
    fun add(num1: Int = 1, num2: Int = 1): Int {
        return num1 + num2
    }
    

    In Kotlin, functions with default arguments have no special representation in the type system, so the only option is to make wrappers passing only part of arguments to them:

    val add0: () -> Int = { add() }
    val add1: (Int) -> Int = { add(num1 = it) }
    val add2: (Int) -> Int = { add(num2 = it) }