Kotlin: Use a lambda in place of a functional interface?
Assuming below that you really need EventHandler
as a separate interface (e.g. for Java interop). If you don't, you can simply use a type alias (since Kotlin 1.1):
typealias EventHandler<T> = (T) -> Unit
In this case a simple lambda will work right away.
But if you don't want to use a type alias, the issue still stands. 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.
To support this syntax:
Events.handler(Handshake::class, EventHandler<Handshake> { println(it.sent) })
You can define a function named EventHandler
:
fun <T> EventHandler(handler: (T) -> Unit): EventHandler<T>
= object : EventHandler<T> {
override fun handle(event: T) = handler(event)
}
To support this syntax:
Events.handler(Handshake::class, { println(it.sent) })
or this:
Events.handler(Handshake::class) { println(it.sent) }
You need to overload the handler
function to take a function instead of EventHandler
:
fun <T> Events.handler(eventType: Class<T>, handler: (T) -> Unit) = EventHandler(handler)
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<T> {
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).