Skip to content

Instantly share code, notes, and snippets.

@FLamparski
Last active January 2, 2016 21:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save FLamparski/c498a508f538018bfd68 to your computer and use it in GitHub Desktop.
Save FLamparski/c498a508f538018bfd68 to your computer and use it in GitHub Desktop.
Let's reimplement while and for loops in Kotlin with its omit-parens-around-last-function-argument syntax

Runnable version: http://try.kotlinlang.org/#/UserProjects/h98israna39btvnahdbghp21jm/ke0lmunnpg0ncu9gvkj8fihpna

Kotlin's function invocation syntax lets you close the parens early and supply the last function argument as a block like so:

foo(bar, baz) { it > squiggle }

Which is equivalent to:

foo(bar, baz, { it > squiggle })

Note that for this to work, the last argument passed to the function must be another function.

I thought, hey, why not use this to build my own loops...

fun wwhile (cond: () -> Boolean, body: () -> Unit) {
if (cond()) {
body()
wwhile(cond, body)
}
}
fun <T> ffor(initialise: () -> T, check: (T) -> Boolean, step: (T) -> T, body: (T) -> Unit) {
var loopvar = initialise()
wwhile({check(loopvar)}) {
body(loopvar)
loopvar = step(loopvar)
}
}
fun main(args: Array<String>) {
var counter = 0
wwhile ({ counter < 5 }) {
counter += 1
print("While iteration $counter\n")
}
ffor({1}, {it <= 5}, {it + 1}) {
i ->
print("For iteration $i\n")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment