An if without an else should return the last line of the body or null


#1

It could be convenient if if would return the contents of the body regardless of whether it is trailed by an else statement.

e.g.

val x = if(someBoolean) "someString"

where x would by of type String?, and have the value "someString" if someBoolean was true, or null if someBoolean was false.

Currently it feels unnecessarily verbose to write

val x = if(someBoolean) "someString" else null

It is not always appropriate to write:

val x = "someString".takeIf { someBoolean }

as there may be some work to perform to create the receiver. e.g.

val x = factory.createObject().takeIf { someBoolean }

and if you want to “optimise” that it gets difficult to read:

val x = factory.takeIf { someBoolean }?.createObject()

#2

It would probably be incompatible to change the meaning of if in this way.

I would like it to look like this:
if?(someBoolean) "someString"


#3

You can also write your own function that would work like this:

val s: String? = someBool.ifTrue { "someString" }


#4

Great, that’s very close to my original idea, though doesn’t quite read as well. i.e. it doesn’t read like English. So this proposal could still be a welcome addition to the language.


#5

I don’t think so, as if cannot be used as an expression without an else. This means there is no incompatibility as it’s not even possible to do. It’s not like it currently returns Unit or null and this would be a breaking change. This would be new functionality and a syntax that currently does not compile.

It just seems logical that if we can write this:

val x = if(someBoolean) a else b

we could write

val x = if(someBoolean) a

it currently gives an error:

‘if’ must have both main and ‘else’ branches if used as an expression

This proposal would make the language a little bit more expressive.


#7

This actually would change the behavior of existing code (not sure in which cases it would break anything, though). An implicit else null in a lambda would change the return type of the lambda from Unit to a nullable type.

`val result = someObject.let { if (someCondition) "result" }`

makes result have type Unit while

`val result = someObject.let { if (someCondition) "result" else null }`

makes result have type String?


#8

I think requirement for else clause in this case to prevent developer from missing the false case.