Implementing C-Style For-Loops In Kotlin

12 Dec 2017

Kotlin does not have C-style for-loops. This is fine because I prefer using the idiomatic for-loops (built to use iterators) anyway. But there is a big problem: Kotlin does not allow dynamic limiting conditions in its for-loops (See this thread). This can sometimes get very annoying. To achieve the same functionality, we have to use a while loop.

Kotlin has two features that I love the most (among many many others):

in case a lambda expression has a single parameter, kotlin puts its value in a special variable it (unless otherwise specified).

if the last parameter of a function is a lambda, that lambda can be put outside the function call.

These two features (along with operator overloading, infix functions, and extension functions) make Kotlin great for writing DSL. We can make a simple polyfill for C-style for-loops like this (oldFor must be inline, otherwise the generated bytecode has poor performance because of 4 lambda arguments):

Notice how we use the special variable it to make oldFor terse. We specify the code block as a lambda expression outside the oldFor call, giving the impression that oldFor is an in-built language construct. Also notice that we can use dynamic limiting condition with oldFor (n gets updated on each pass).