So, the code below is an event system that performs the following actions:
- Assign an integer id to a lambda expression
- Put lambda identifier in mutable event
- Maps integer identifier to lambda expression
- Returns an identifier (can be used later to remove events from lambda)
The code is as follows:
class EventHandler {
companion object {
val handlers = HashMap<KClass<out Event>, MutableSet<Int>>()
val idMap = HashMap<Int, (Event) -> Unit>();
fun <T : Event> register(event: KClass<T>, handler: (T) -> Unit): Int {
var id: Int = 0;
while(idMap[id] != null) {
id++;
}
var list = handlers.getOrPut(event, {mutableSetOf()});
list.add(id);
idMap[id] = handler;
return id;
}
}
}
The intended use of this method would be something like this:
EventHandler.register(ChatEvent::class) { onChat ->
println(onChat.message)
}
The following line contains an error: idMap[id] = handler;
The error is due to the fact that the handler has a type (T) -> Unit, although idMapit must be there to add it to it (Event) -> Unit. Although I said that I Tshould expand Eventwhen I created it, so this should not be a problem. Does anyone know why this happens if there is a solution?