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?
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.
Explanation- We have defined a function using fun keyword whose return type in Unit by default.
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.
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.
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) }
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