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 this:
Events.handler(Handshake::class, object : EventHandler<Handshake> {
override fun handle(event: Handshake) {
println(event.sent)
}
})
With a more convenient:
Events.handler(Handshake::class, EventHandler<Handshake> { println(it.sent) })
For some reason in reference to EventHandler
:
More preferably however I'd like to use something even shorter like this:
Events.handler(Handshake::class, { println(it.sent) })
Or use the advertised feature to use the method like this:
Events.handler(Handshake::class) { println(it.sent) }
This is my Events
object:
import java.util.*
import kotlin.reflect.KClass
object Events {
private val map = HashMap<Class<*>, Set<EventHandler<*>>>()
fun <T : Any> handler(eventType: KClass<T>, handler: EventHandler<T>) {
handler(eventType.java, handler)
}
fun <T> handler(eventType: Class<T>, handler: EventHandler<T>) = handlers(eventType).add(handler)
fun post(event: Any) = handlers(event.javaClass).forEach { it.handle(event) }
operator fun plus(event: Any) = post(event)
private fun <T> handlers(eventType: Class<T>): HashSet<EventHandler<T>> {
var set = map[eventType]
if (set == null) {
set = HashSet<EventHandler<*>>()
map.put(eventType, set)
}
return set as HashSet<EventHandler<T>>
}
}
And my EventHandler
interface:
@FunctionalInterface
interface EventHandler<T> {
fun handle(event: T)
}
Handshake::class.java
for the first argument? In any case, try Ctrl + P to view the possible parameters of the function. – Kirill RakhmanEvents.handler(Handshake::class) { println(it.sent) }
— this syntax has nothing to do with inline functions – Andrey Breslavhandler
. @AndreyBreslav @Jonathan-Beaudoin Adjusted the initial question. – Jire