Filter a list by type



Is it possible in kotlin to filter element of list by these type.
My list contain element which are generic
where IDomainEvent is en interface:
This is the model :

interface IDomainEvent 
data class WarriorCreated(val content: String): IDomainEvent
data class WarriorDeleted(val content: String = ""): IDomainEvent

I thied with the methode of List : filterIsInstance() but with no success.

To be more precise this is my use case.
I receive an event of type IDomainEvent which can be a WarriorCreated or WarriorDeleted and depending of the tkind of IDomainEvent I want to retrieves only subscribers of the desired type

private val subscribers = mutableSetOf<>()<IEventSubsriber<IDomainEvent>> >()

override fun  publish(evt: IDomainEvent) {
    // filter susribers by kind of events


Thanks and regards


No, you cannot filter on the type of a generic parameter which is a limitation of the JVM not Kotlin specifically. The JVM uses type erasure for generics so the generic type information doesn’t actually exist anymore at runtime.


Sad to read that :frowning:

So, I’m using a map instead.
private val subscribers = mutableMapOf<Class,MutableSet<IEventSubsriber>>()

It workes. but it is less nicer :frowning:

Thanks four your answer again :slight_smile: