I am struggling to understand how a function type with receiver works in Kotlin. I don't understand why we can use (String) -> Unit and String.() -> Unit in my code indistinctively
fun main() {
var showStringFunction1: (String) -> Unit = ::showString
showStringFunction1("Hey")
var showStringFunction2: String.() -> Unit = ::showString
showStringFunction2("Hey")
}
fun showString(x: String): Unit { println(x) }
The difference between these only matters when either:
You are passing a lambda. It affects whether the first parameter is
thisor a named parameter inside the lambda. If you pass something other than a lambda, the receiver can be thought of as the first function argument.You are invoking it. The receiver version is more versatile because you can also choose to invoke it like an extension function. But you can also invoke it as if the receiver is the first function argument.
A related concept comes when passing a function argument. So,
showStringcould be an extensionfun String.showString(): Unitand it could be passed to either of your variables in the example.