user2498079
user2498079

Reputation: 3012

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?

Upvotes: 1

Views: 3047

Answers (4)

k314159
k314159

Reputation: 11140

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)

Upvotes: 0

Tenfour04
Tenfour04

Reputation: 93629

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.

Upvotes: 3

Praveen
Praveen

Reputation: 3486

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.

Upvotes: 1

Stepan Kulagin
Stepan Kulagin

Reputation: 505

Your second variant is workable, just set ! before is

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

Upvotes: 1

Related Questions