简体   繁体   中英

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.

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)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM