Kotlin:使用 lambda 代替功能接口?
在Java中,我们可以做到这一点。Events.handler(Handshake.class, hs -> out.println(hs));
然而,在Kotlin中,我试图复制行为来替换它:
Events.handler(Handshake::class, object : EventHandler<Handshake> {
override fun handle(event: Handshake) {
println(event.sent)
}
})
具有更方便的:
Events.handler(Handshake::class, EventHandler<Handshake> { println(it.sent) })
出于某种原因,请参阅:EventHandler
但是,更可取的是,我想使用更短的东西,如下所示:Events.handler(Handshake::class, { println(it.sent) })
或者使用播发功能来使用如下方法:Events.handler(Handshake::class) { println(it.sent) }
这是我的对象:Events
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>>
}
}
还有我的界面:EventHandler
@FunctionalInterface
interface EventHandler<T> {
fun handle(event: T)
}