Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 293
pondermatic Avatar asked Mar 30 '16 00:03

pondermatic


People also ask

How do you pass a default parameter in Kotlin?

Kotlin Default Argument In Kotlin, you can provide default values to parameters in function definition. If the function is called with arguments passed, those arguments are used as parameters. However, if the function is called without passing argument(s), default arguments are used.

What is the default return type of any functions defined in Kotlin?

Explanation- We have defined a function using fun keyword whose return type in Unit by default.

What is the default type of argument used in constructor in Kotlin?

Kotlin Default arguments – If the function is called without passing arguments then the default arguments are used as function parameters. In other cases, if arguments are passed during a function call then passed arguments are used as function parameters.

What is () -> unit in Kotlin?

Unit in Kotlin corresponds to the void in Java. Like void, Unit is the return type of any function that does not return any meaningful value, and it is optional to mention the Unit as the return type. But unlike void, Unit is a real class (Singleton) with only one instance.


1 Answers

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) }
like image 196
hotkey Avatar answered Oct 03 '22 21:10

hotkey