There is a lib which provides following API: `susp...
# announcements
c
There is a lib which provides following API:
suspend inline fun <reified T : Event> Client.addHandler(noinline action: suspend (T) -> Unit)
I have a handler interface
Copy code
interface EventHandler<T : Event> {
    suspend fun handle(event: T)
}
And I have a list of handlers which is injected into my application:
val handlers: List<EventHandler<*>>
Each handler is defined as
MyHandler : EventHandler<MyEvent>
I need to somehow add these handlers to the client:
handlers.forEach { client.addHandler(it::handle) }
I'm getting
Cannot use 'Nothing' as reified type parameter
at the
.addHandler
What can I do to work around it?
d
You need to make a nom-reified version of addHandler that takes a class parameter.
Then use some form of reflection or polymorphism to fetch the class representing your event type
Or add a function to your event handler interface to register itself to a client, calling the addHandler function with the right type.
c
I've also actually found these two options - one go through reflection - sifting through generic interfaces of the class (which I'd like to avoid) second visitor pattern-like approach. The latter's downside is repetition, each implementation of the handler would have one and the same code:
Copy code
override suspend fun registerTo(client: Client) {
    client.addHandler(action = this::handle)
}
But I guess, it's the lesser of the two evils
in fact in this case I'll probably change the interface:
Copy code
interface EventHandler {
    suspend fun registerTo(client: Client)
}
and implementations will become:
Copy code
class MyEventHandler : EventHandler {
  override suspend fun registerTo(client: Client) {
    client.addHandler<MyEvent> {
      // stuff
    }
  }
}