Using “when”

When is a very interesting feature in Kotlin, it’s more powerful than Java’s switch which only allows enum constants, strings and numbers as branch conditions. When allows any objects.

Let’s create a LeJOS project in IntelliJ IDEA (see previous post to learn how to) and add a Kotlin file named Main.

package com.kotlinrobots.buttons

import lejos.hardware.Button

fun main(args: Array<String>) {

    println("Showing keys: ")

    for (i in 1..10) {
        val key = Button.waitForAnyPress()

        when (key) {
            Button.ID_UP -> println("UP")
            Button.ID_ENTER -> println("OK")
            Button.ID_DOWN -> println("DOWN")
            Button.ID_RIGHT -> println("RIGHT")
            Button.ID_LEFT -> println("LEFT")
            Button.ID_ESCAPE -> println("ESCAPE")
            else -> println("UNKNOWN")

As you might have already noticed by now, in Kotlin there is no need to write semicolon at the end of every line and we don’t need to create a class in order to have a main function.

Line 7: it’s not mandatory to use LCD class to write output on the brick’s screen, unless you want to be specific about the position.

Line 9: shows how to create a for-loop in Kotlin using ranges. In this case we will have 10 iterations.

Line 12-20:¬†shows how readable Kotlin code is, you can even read it and say: when key is ID_UP which is 1, let’s print UP; when key is ID_ENTER, let’s print OK, and so on. No more break statements!

Create a LeJOS Run Configuration and run it! Press the buttons on your brick and see the results on the screen:

Source code


Leave a Reply

Your email address will not be published. Required fields are marked *