Kotlin: A for loop that counts up to some maximum integer value

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.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.