i am doing a bunch of: ```val value = if (someCond...
# getting-started
p
i am doing a bunch of:
Copy code
val value = if (someCondition) {
  // compute value
} else {
  null
}
the else branch is always just
null
.. is there a more idiomatic way to write this?
someCondition
is not a null check otherwise i would use
let
j
If the computation is not expensive you could use:
Copy code
val value = computeValue().takeIf { someCondition }
p
thought of that.. only problem is that
computeValue()
actually blows up if
someCondition == false
1
e
if it takes a non-null argument then
Copy code
val value = arg.takeIf { someCondition }?.let { computeValue(it) }
but there's nothing as clear as the
if
statement
3
j
I was about to write just that ☝️
If the computation and/or the condition are complex expressions, extract them into a function, and then keep the
if
statement:
Copy code
val value = if (condition) computeValue() else null
p
im looking for something like this i guess:
Copy code
private fun <T> getIf(condition: Boolean, supplier: () -> T?): T? {
    return if (condition) {
        supplier()
    } else {
        null
    }
}
oh yeah, that’s exactly what i need.. cool.. dont care about smart casting so i will implement my own for now