Utility Functions

The Kotlin standard library offers a plethora of useful and clever functions to ease development and create cleaner code.

Here you'll find my favorites explained.

Marking Code as TODO

A common approach to mark code as TODO and not implemented yet in Java is to throw new UnsupportedOperationException("Not implemented yet").

While this really is not much code, Kotlin still offers a better approach with its TODO(reason: String) function which just throws a NotImplementedError which directly states that the operation is not implemented yet instead just "not supported" liken in Java. The "reason" parameter is optional.

Using TODO instead of throwing the exception manually makes it easy to find existing TODOs (hence, calls to this function) using your IDE's standard "find references" feature and just looks nice and crisp in code.

Repeating a Block of Code x times

In Java, often times you do

for (int i=0; i<x; i++) {
    // some code

to repeat a piece of code x times.

Kotlin's range operator does not really improve things:

for (index in 0..x - 1) {
        // some code

even sporting until it still looks bulky:

for (index in 0 until x) {
        // some code

Why not simply state that all you want is to repeat the given code x times?

That's what repeat is for:

repeat(x) {
        // some code

so easy and clear! Thanks, Kotlin designers!