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.
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.
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 }`
I second this, I think it would be useful. It would of course be trivial to write a custom method ifTrue(condition: Boolean, action: () -> T), as suggested above, but the name ifTrue just looks terrible and confusing, and nothing that I’ve considered looks nearly as elegant as the keyword if.