title: Elegant event handler with generics in Kotlin
body: <p>I'm trying to build an event handler with events indexed by class. You would register to listen for events of class <code>InterestingEvent : Event</code> (for example) and would be notified whenever a new <code>InterestingEvent()</code> was sent to the manager.</p>
  
  <p>I can't get the Kotlin generic code to work right though. This is the best I can do so far:</p>
  
  <pre><code>class EventManager{
      private val listeners: MutableMap&lt;KClass&lt;out Event&gt;, MutableList&lt;EventListener&lt;in Event&gt;&gt;&gt; = HashMap()
  
      fun &lt;T : Event&gt; register(event: KClass&lt;out T&gt;, listener: EventListener&lt;T&gt;) {
          val eventListeners: MutableList&lt;EventListener&lt;T&gt;&gt; = listeners.getOrPut(event) { ArrayList() }
          eventListeners.add(listener)
      }
  
      fun notify(event: Event) {
          listeners[event::class]?.forEach { it.handle(event) }
      }
  }
  </code></pre>
  
  <p>My <code>getOrPut</code> call wants a <code>MutableList&lt;EventListener&lt;T&gt;&gt;</code> but found <code>MutableList&lt;EventListener&lt;in Event&gt;&gt;</code> instead.</p>
  
  <p>Ideally I'd get rid of the KClass parameter to <code>register</code> as well but I don't think that's possible.</p>
  
  <p>Is it possible to do what I'm trying here?</p>