mardi 7 février 2017

Kotlin reflection + generics

EDIT 1: Changed title, my bad.

I have an interface Event:

interface Event

And some classes that implement it, like CustomEvent:

class CustomEvent : Event { ... }

What I've been trying to do now is: given a method that has an event as a parameter (so, any class that implements the Event interface), like this

fun onCustomEvent(event: CustomEvent) {
    ...
}

, I want to add that event to a list. Thus, this list will end up holding a bunch of different events.


In Java I belive it would be something like this (might not be 100% accurate):

List<Class<? extends Event>> eventsList;

....

Class<?> param = methodThatHasSomeEventAsParam.parameterTypes[0];

if (Event.class.isAssignableFrom(param)) {
    Class<? extends Event> actualParam = (Class<? extends Event>) param;
    eventsList.add(actualParam); // Adds CustomEvent to the events list.
}


But as for Kotlin, I'm really not sure how to use the generics properly, specifically what would be the correct way to translate

Class<? extends Event> 

to Kotlin, keeping the same behaviour as the Java code above.

Thanks in advance.





Aucun commentaire:

Enregistrer un commentaire