user3610570
user3610570

Reputation: 21

In Kotlin, why is the default argument not passed after the function being assigned to a variable?

I created a function with default argument, then save the function to a variable.

But when I invoked the function through the variable, the default argument is not passed.

fun main(args : Array<String>) {
    printNum()
    val fn = ::printNum
    fn(0)
    fn()    // error: no value passed for parameter 'i'
}
fun printNum(i: Int = 10) = println(i)

Upvotes: 0

Views: 329

Answers (1)

s1m0nw1
s1m0nw1

Reputation: 81899

That's because you're using a method reference. Your fn variable is of type KFunction<Int, Unit>. When you call fn() it's being compiled to fn.invoke(), which expects an integer as an argument here.

Upvotes: 2

Related Questions