Add Unless Keyword


#1

Hey there,
it would be really nice if there was an “unless” keyword, similar to Ruby, in Kotlin.
It basically is the “not if” keyword, so if something is not true, it runs the block, and it can have the else block too.
I couldn’t find any thread about this, sorry if there is one already.

Thanks


#2

I wonder what the added value of this is over just using an if with a not (that is even less typing) or reversing the consequences. For me, this feature does not survive the -100 points rule.


#3

You can easily recreate the unless behavior in Kotlin like this:
fun unless(condition: Boolean, block: () -> Unit){
if (!condition) block()
}

And it can be used like this
unless(false) { println("unless in Kotlin") }

I am not sure though if it is possible to create the else block


#4

Your unless function should be declared as inline, which will allow using return within the block body (just like ordinary if).


#5

Some more complete solutions, (else and infix options)

inline fun <T> unless(bool: Boolean, block: () -> T): T? = if (!bool) block() else null

infix fun <T> (() -> T).unless(bool: Boolean): T? = if (!bool) this() else null

inline infix fun <T> T?.`else`(block: (() -> T)): T? = this ?: block()

which can be used like this:

val e = unless(false) {
    "test"
} `else` {
    "aye"
}
println(e)

val q = { "test" } unless true `else` { "aye" }
println(q)

which prints:

test
aye

feel free to change the third function name from else if you want to remove the two `.


#6

Just realized the else can actually return T instead of T? since it’s never null, was just writing a lot of T? returns so I didn’t think about it lol