In Java we can do this
Events.handler(Handshake.class, hs -> out.println(hs));
In Kotlin however I am trying to replicate the behavior to replace thi
A lot of nice things has happened to Kotlin since @andrey-breslav posted the answer. He mentions:
It is that Kotlin only does SAM-conversion for functions defined in Java. Since Events.handler is defined in Kotlin, SAM-conversions do not apply to it.
Well, that's no longer the case for Kotlin 1.4+. It can use SAM-conversion for Kotlin functions if you mark an interface as a "functional" interface:
// notice the "fun" keyword
fun interface EventHandler {
fun handle(event: T)
}
You can read the YouTrack ticket here: https://youtrack.jetbrains.com/issue/KT-7770. There's also an explanation why Kotlin needs a marker for such interfaces unlike Java (@FunctionalInterface
is only informational and has no effect on the compiler).