Ok so the code below is an event system that does the following:
- Assigns an integer id to a lambda expression
- Puts the lambda's id in an event's mutable set
- Maps the integer ID to the lambda expression
- Returns the id (can be used later to remove events from the lambda)
The code is as follows:
class EventHandler {
companion object {
val handlers = HashMap<KClass<out Event>, MutableSet<Int>>()
val idMap = HashMap<Int, (Event) -> Unit>();
/**
* @param event Class of the event you are registering
* @param handler What to do when the event is called
*/
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)
}
There is an error at the following line: idMap[id] = handler;
The error is because the handler is of type (T) -> Unit, although it needs to be (Event) -> Unit in order to add it to the idMap. Although I said that T should extend Event when I created it, so this shouldn't be a problem. Does anyone know why this happens of if there is a solution?