Explicit "do nothing" construct?


#1

Sometimes it is useful to have explicit construct of “do nothing”. It could potentially increase readability. What comes in mind is empty methods and lambdas, prototypes, default action in when clause and so on.

As I know, there are two options: {} and Unit. For me, Unit seems misleading. Also, it is object.
{} is more readable, but one can confuse it with lambda or it can be autoformatted to {\n}, which looks ugly:

when (state) {
    State.FAIL -> doSomething()
    State.FAIL -> {
        doOther()
        Thing()
    }
    else -> {
    }
}

compare it to this

when (state) {
    State.FAIL -> doSomething()
    State.FAIL -> {
        doOther()
        Thing()
    }
    else -> pass
}

Also, concept of empty block as “do nothing” is not obvious. There are some questions on SO like “Do nothing keyword in C#” or “Empty if statements”.
Some languages do have it, e.g. Python has ‘pass’ (due to lang formatting requirements)

I think it would be easy to add a special keyword for this to language and it would greatly improve readability in some cases.


#2

Adding any keyword to the language is not easy at all, because it will break all code that has used that word as an identifier. Given the backwards compatibility promises given at the release of Kotlin 1.0, this needs very strong arguments.

As you correctly write, Kotlin has two existing possibilities to express the same idea with the same amount of characters. Learning the meaning of Unit or an empty pair of braces in this context is not much harder than learning a new keyword. Therefore, the argument doesn’t seem strong.

Not to mention the fact that you can define it yourself if you think that it will make your code more readable: val pass: Unit = Unit


#3

Thanks for fast response. Did not think about it.
I’ll consider using val pass.