Home > Mobile >  Filtering list based on instance type
Filtering list based on instance type

Time:05-05

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?

CodePudding user response:

Your second variant is workable, just set ! before is

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

CodePudding user response:

There's also a filterNot method for the list, which returns a list after removing all the elements that match the passed predicate.

objectList.filterNot { 
    it is object2 || it is object3
}
    

This would return a list after removing all elements from objectList that would be of type object2 or object3.

CodePudding user response:

The point of filterIsInstance is that it returns a List with a more specific type than the input Iterable you gave it. For example, if you have a List<Number> and call filterIsInstance<Int>() on it, the return value is the more specific List<Int>.

If you are doing the reverse, there is no logical more specific type it can give you, so there is no reason for the standard library to include filterIsNotInstance. You can simply use filter or filterNot instead with a lambda that uses an is or !is check.

CodePudding user response:

The filterIsInstance function and the is keyword work on types, but what you're providing as arguments are instances. Therefore, I think you need something like this:

objectList.filter { it::class != object2::class && it::class != object3::class)
  • Related