Home > Software design >  Kotlin SAM interface and method reference
Kotlin SAM interface and method reference

Time:02-02

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?

CodePudding user response:

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.

  •  Tags:  
  • Related