Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin SAM interface and method reference

Tags:

kotlin

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?

like image 714
Alex T Avatar asked Nov 15 '25 14:11

Alex T


1 Answers

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.

like image 90
Joffrey Avatar answered Nov 18 '25 21:11

Joffrey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!