Reputation: 333
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.
Upvotes: 3
Views: 2297
Reputation: 333
Thanks for the help; this would be the way to do it in Kotlin:
// <? extends Event> in Java ==> <out Event> in Kotlin.
val myList: MutableList<Class<out Event>>
val param: Class<*> = methodThatHasSomeEventAsParam.parameterTypes[0]
if (Event::class.java.isAssignableFrom(param)) {
param as Class<out Event>
myList.add(param)
}
Upvotes: 5