I am a bit confused why I can do the following
val outputter1: (s: String) -> Unit = ::println
but when I do
val outputter2: Outputter = ::println
given
fun interface Outputter {
fun output(output: String)
}
I get a compilation error
None of the following functions can be called with the arguments supplied.
println() defined in kotlin.io
println(Any?) defined in kotlin.io
...
Shouldn't method references translate to SAM inteface types as well as Function types?
Apparently, SAM conversions must be explicit in assignments (despite the type declaration) using the auto-generated adapter functions:
val outputter2: Outputter = Outputter { println(it) } // OK
val outputter3: Outputter = Outputter(::println) // OK
val outputter4: Outputter = { s: String -> println(s) } // compile error
But they are inferred fine in function calls:
fun main() {
takesOutputter(::println) // OK
}
fun takesOutputter(o: Outputter) {
o.output("test")
}
For reference, checkout the doc on Kotlin SAM conversions, and this part in the Java interop section which gives more examples of SAM conversions.
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