Martin
Martin

Reputation: 2914

How to check if specific class is inside list and return index?

I have list of objects. These objects are sharing same abstract class. Is there any way how to get indexOf specific object based on class name?

Something like this:

open fun getScreenIndex(screen: Class<out FlowScreen>): Int{
     return flowList.indexOf(screen)
}

And I would call it like this:

getScreenIndex(AccountScreen::class.java)

Im building dynamic ViewPager which will be populated by screens and I need a way how to switch pages, but I don't wanna use indices (random numbers inside code - its confusing). Its way better to just call screen name. There wont be a case, when you will have same class twice in that list.

Upvotes: 1

Views: 161

Answers (1)

darshan
darshan

Reputation: 4569

Try like this:

val index = flowList.indexOfFirst { item -> item::class.java == AccountScreen::class.java }

You could also change Class<out FlowScreen> to Class<*>

Upvotes: 2

Related Questions