https://kotlinlang.org logo
#getting-started
Title
# getting-started
m

Marcin Wisniowski

09/06/2023, 11:09 PM
I need to check if an object is any of 4 possible types, is there any cleaner way than
item is A || item is B || item is C || item is D
?
j

Joffrey

09/06/2023, 11:11 PM
I think it depends on how you want to use this condition. If your goal here is to avoid repeating the
item
subject, you could use a
when
like this:
Copy code
when (item) {
    is A, is B, is C, is D -> doTheThing()
    else -> dontDoTheThing()
}
The best would of course be to define a parent type for A, B, C, and D and check if
item
is of the parent type (e.g. a sealed interface)
👍 1
m

Marcin Wisniowski

09/06/2023, 11:13 PM
It is a sealed interface with 8 types, but I need to check if it's any of 4 of them. It's inside a list
filter {}
I guess I could define a separate empty interface to "mark" these 4.
j

Joffrey

09/06/2023, 11:14 PM
Exactly
and if there is something so special about these 4 types that they are treated in a common way, maybe they share properties, or should have common methods, which would go into that interface
Using a parent interface also allows to use
.filterIsInstance<TheParentInterface>()
which yields a list of the new element type, which allows to make use of this information further down the pipeline
m

Marcin Wisniowski

09/06/2023, 11:17 PM
It's actually a list of object that have the interesting items as a field, so it's now `.filter { it.item is MarkerInterface }``
j

Joffrey

09/06/2023, 11:17 PM
Got it, it will depend on the use case of course
👍 1