poohbar
03/30/2022, 5:03 PMval value = if (someCondition) {
// compute value
} else {
null
}
the else branch is always just null
.. is there a more idiomatic way to write this?poohbar
03/30/2022, 5:03 PMsomeCondition
is not a null check otherwise i would use let
Joffrey
03/30/2022, 5:04 PMval value = computeValue().takeIf { someCondition }
poohbar
03/30/2022, 5:04 PMcomputeValue()
actually blows up if someCondition == false
ephemient
03/30/2022, 5:05 PMval value = arg.takeIf { someCondition }?.let { computeValue(it) }
ephemient
03/30/2022, 5:06 PMif
statementJoffrey
03/30/2022, 5:06 PMJoffrey
03/30/2022, 5:07 PMif
statement:
val value = if (condition) computeValue() else null
ephemient
03/30/2022, 5:07 PMpoohbar
03/30/2022, 5:07 PMprivate fun <T> getIf(condition: Boolean, supplier: () -> T?): T? {
return if (condition) {
supplier()
} else {
null
}
}
poohbar
03/30/2022, 5:10 PM