Extension function for 'if (condtion) .. else null'

Probably it’s worth adding an extension function that would reduce this code:

return if (condition) {
    computeValue()
} else {
    null
}

to this:

return computeIf(condition) {
    computeValue()
}

The reason takeIf wouldn’t work here is that it’d look like this

takeIf { condition }?.let { computeValue() }

Which looks even clumsier than the original thing

2 Likes

You can remove the braces in your snippet:

return if (condition) computeValue() else null

which is roughtly as many characters as your proposed computeIf

1 Like

The same applies to takeIf, however there’s a separate extension for that :slight_smile:

I think, it could be quite handy and elegant to be able to leave out this else-null condition

I like it, although I would name it computeIfOrNull which would make it even longer :wink:
giving takeIf a simple boolean would work too, isn’t it?

Take if wouldn’t work here because I wouldn’t like to make the computation before validating the boolean

You’re correct takeIf would indeed not work…
i meaned:

takeIf(condition)?.let{ 
    ComputeValue() 
}

But the naming wouln’t declare it’s intention.

condition would have to be a lambda for your example to work