I need to check if an object is any of 4 possible ...
# getting-started
m
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
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
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
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
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
Got it, it will depend on the use case of course
👍 1