Reputation: 1563
I want to have a list of Activities
and I want to loop through it to check if the current Activity
is
of this type then do something.
Current code:
if (activity is ActivityA || activity is ActivityB || activity is ActivityC) dosmth()
How to create an ArrayList
of these activities and loop through them in a method? I have a difficulty determining the Type
which should be used.
Upvotes: 0
Views: 499
Reputation: 170723
I'd consider writing your code as
when(activity) {
is ActivityA, is ActivityB, is ActivityC -> dosmth()
}
If you do want a collection (e.g. because the list of classes may depend on something) you can write
val activityClasses = listOf(ActivityA::class, ActivityB::class, ActivityC::class).map { it.java }
if (activityClasses.any { it.isInstance(activity) }) {
doSmth()
}
Upvotes: 1
Reputation: 18243
Just to repeat less code, I used:
if (activity::class in setOf(ActivityA::class, ActivityB::class, ActivityC::class)) {
dosmth()
}
Upvotes: 2