title: Handle generic listeners of event bus in Kotlin
body: <p>My goal is to implement very simple event bus in Kotlin without any 3rd party libraries. I accomplished that with the code below.</p>
  
  <pre><code>class EventListener&lt;T&gt;(
      val owner: Any,
      val event: Class&lt;T&gt;,
      val callback: (T) -&gt; Unit
  )
  
  interface IEventBus {
      fun &lt;T&gt; subscribe(owner: Any, event: Class&lt;T&gt;, callback: (T) -&gt; Unit)
      fun unsubscribe(owner: Any)
      fun &lt;T&gt; push(event: T)
  }
  
  class EventBus : IEventBus {
      private val _listeners = mutableListOf&lt;EventListener&lt;*&gt;&gt;()
  
      override fun &lt;T&gt; subscribe(owner: Any, event: Class&lt;T&gt;, callback: (T) -&gt; Unit) {
          val listener = EventListener(owner, event, callback)
          _listeners.add(listener)
      }
  
      override fun unsubscribe(owner: Any) {
          _listeners.removeAll {
              it.owner == owner
          }
      }
  
      override fun &lt;T&gt; push(event: T) {
          _listeners.forEach { listener -&gt;
              try {
                  val l = listener as EventListener&lt;T&gt; // is always a success
                  l.callback(event)                    // throws an exception if can't handle the event
              } catch (ex: Exception) { }
          }
      }
  }
  </code></pre>
  
  <p>And then the usage would be like this:</p>
  
  <pre><code>// register listener
  bus.subscribe(this, String::class.java) {
      print(it)
  }
  // push an event (from somewhere else in the project)
  bus.push("Hello world!")
  </code></pre>
  
  <p>It works and is completely usable, however I am not satisfied with it... Casting <strong>listener as EventListener</strong> will always return something and then if <strong>l.callback(event)</strong> can't handle the event type it will throw an exception. So if there are many listeners subscribed then it will generate many unwanted exceptions that will just be ignored.</p>
  
  <p>I would prefer doing some kind of check first, like:</p>
  
  <pre><code>if (listener is EventListener&lt;T&gt;)
      listener.callback(event)
  </code></pre>
  
  <p>But I found out that JVM loses information about the generic types after the compilation. I also found out that it can be bypassed using kotlin's <strong>inline</strong> and <strong>reified</strong>, however those can not be used on a method that comes from an interface...</p>
  
  <p>So my question is do you know any more elegant way to handle such generic problem?</p>