TabLayout iterator

When using Kotlin, I like to use all collection functions, like find, indexOf, filter, map etc. And now with extension functions we can use Java classes in same way. For example, we can iterate ViewGroup children:

viewGroup.children.filterIsInstance<TextView>().forEach {
it.setTextColor(Color.RED)
}

I created same extension for TabLayout, to iterate tabs:

fun TabLayout.tabsIterator(): MutableIterator<TabLayout.Tab> =
object : MutableIterator<TabLayout.Tab> {
private var index = 0
override fun hasNext() = index < tabCount
override fun next() = getTabAt(index++) ?: throw IndexOutOfBoundsException()
override fun remove() = removeTabAt(--index)
}

val TabLayout.tabsItems: Sequence<TabLayout.Tab>
get() = object : Sequence<TabLayout.Tab> {
override fun iterator() = tabsIterator()
}

Usage example:

tabLayout.tabsItems.find { it.tag == "find_me" }?.select()

It’s nice to write shorter code.

--

--