By Alvin Alexander. Last updated: December 1, 2018
As a brief note to self, I was just converting some Java code to Kotlin, and the correct way to convert this Java for
loop that uses i
as a counter:
for (int i=0; i<tabLayout.tabCount; i++) { ...
is with this Kotlin for
loop:
for (i in 0 until tabLayout.tabCount) { ...
The key there for me is the 0 until
part of the syntax.
FWIW, here’s the full Kotlin for
loop:
for (i in 0 until tabLayout.tabCount) {
val tab = tabLayout.getTabAt(i)!!
// more code here that uses `tab`
}
And here’s an example of this technique in the Kotlin REPL:
>>> for (i in 0 until 3) { println(i) }
0
1
2
There are other ways to do this, but when your Kotlin for
loop needs to count from zero up to some integer value, this for
loop technique works.