Consumer playing weird in Kotlin

I am just returning to Kotlin (transition from java) and I noticed that the use is Consumermore complicated than it seems.

class EventBus(controller: Controller) {
    private val consumerMap : MutableMap<KClass<out Event>, MutableSet<Consumer<out Event>>> = ConcurrentHashMap()
    private val controller : Controller = controller

    public fun <T : Event> register(clazz: KClass<T>, handler: Consumer<T>) {
        consumerMap.getOrPut(clazz, { HashSet() }).add(handler)
    }

    public fun <T : Event> post(event : T) {
        consumerMap[event.javaClass.kotlin]?.forEachIndexed { i, handler ->
            controller.getLogger().trace("Firing handler ${i + 1} for event ${event.javaClass.name}")
            handler.accept(event)
        }
    }
}

I am trying to make a simple class to fire dead main events, the only problem is that the IntelliJ accept method does not exist. However, when I try to create a new consumer and use it right away, the accept method exists and works as expected.

http://pksv.co/go/myOeEvTE

Is there anything I might have missed or missed?

+4
source share
1 answer

Stupid to me. I woke up in my head for so long. Replacing use Consumer<out Event>(and others Consumer) with the help (Event) -> Unitcleared everything!

, :

class EventBus(controller: Controller) {
    private val consumerMap : MutableMap<KClass<out Event>, MutableSet<(Event) -> Unit>> = ConcurrentHashMap()
    private val controller : Controller = controller

    public fun <T : Event> register(clazz: KClass<T>, handler: (T) -> Unit) {
        consumerMap.getOrPut(clazz, { HashSet() }).add(handler as (Event) -> Unit) // hacky cast :-)
    }

    public fun <T : Event> post(event : T) {
        consumerMap[event.javaClass.kotlin]?.forEachIndexed { i, handler ->
            controller.getLogger().trace("Firing handler ${i + 1} for event ${event.javaClass.name}")
            handler.invoke(event)
        }
    }
}
+4

Source: https://habr.com/ru/post/1622554/


All Articles