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

Time:12-09

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.

CodePudding user response:

Try like this:

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

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

  • Related