Search code examples
javaandroidkotlinswitch-statementbreak

How to break kotlin when clause?


Suppose that I have code in Java

@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
    switch (motionEvent.getActionMasked()) {
            case MotionEvent.ACTION_DOWN: {
                if (something()) {
                     break;
                }
                // do more stuff here
                break;
            }
    }
    return false;
}

I rewrote it for something like this, but I'm not sure it's correct and it doesn't have any flaws.

override fun onTouch(view: View, motionEvent: MotionEvent): Boolean {
    when (motionEvent.actionMasked) {
            MotionEvent.ACTION_DOWN -> {
                if (something()) {
                    return false
                }
                // do more stuff here
            }
    }
    return false
}

What is the best way to emulate/implement in kotlin break like in the java switch statement?


Solution

  • Kotlin when expressions are very different from Java switch expressions in terms of execution. In Java, a switch call will try to run the next available case if you don't break. In Kotlin as soon as the first condition is met, the when call automatically breaks so you don't really need a break statement inside a Kotlin when expression.