Type signature for Kotlin function with default parameters
Asked Answered
L

1

6

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?

Legg answered 30/3, 2016 at 0:20 Comment(3)
try to make zero-parameters function wrapper over adder, I don't know if you there is some syntactic sugar in kotlin to create ad hoc anonymous functions within another function declaration. Something like .... = :: ( ()->(add()) ) ):Int{.....Fattal
no idea about the language, but in general making wrapper seems solving your issue.Strikebreaker
Yup, creating a wrapper works, but I'm wondering if there's a way I can do this with type signatures. I expect it's not possible.Legg
C
10

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) }
Consistent answered 30/3, 2016 at 0:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.