Search code examples
listkotlinfiltercollectionsinstance

Filtering list based on instance type


I've a list of different objects extending from the same parent class. I want to remove only 2 objects from the list based on the instance type. I found filterInstanceOf() but it actually returns the object that matches this filter.

val objectList = listOf(object1, object2, object3, object4)

I want to do something like:

objectList.filterInstanceIsNot(object2).filterInstanceIsNot(object3)

or

objectList.filter { it is! object2 && it is! object3)

how can I do it?


Solution

  • Your second variant is workable, just set ! before is

    objectList.filter { it !is object2 && it !is object3)