Mark
03/01/2021, 2:41 PMval resultOrNull = firstAttemptOrNull() ?: run {
if (someConditionMet()) {
secondAttemptOrNull()
} else {
null
}
}
dfriehs
03/01/2021, 3:41 PMrun
block (and consider a when
block instead of if
):
val resultOrNull = firstAttemptOrNull() ?: when {
someConditionMet() -> secondAttemptOrNull()
else -> null
}
Joel
03/01/2021, 7:16 PMfirstAttemptOrNull() ?: secondAttemptOrNull()?.takeIf { someConditionMet() }
downside is that it will run secondAttemptOrNull
even if someConditionMet
is false and then drop result on the floor. Unsure if there's a helper that runs the conditional first, like an if
statement that runs a lambda.firstAttemptOrNull() ?: if (someConditionMet()) secondAttemptOrNull() else null
is also validMark
03/02/2021, 1:58 AMinline fun <R> otherwiseIf(condition: Boolean, block: () -> R): R? = if (condition) {
block()
} else {
null
}
And then we can do:
val resultOrNull = firstAttemptOrNull()
?: otherwiseIf(someConditionMet) {
secondAttemptOrNull()
}
Joel
03/02/2021, 2:00 AMif
I'd have to question if we're only doing it because we can 🙂someConditionMet().ifTrue { secondAttemptOrNull() }
but have never been happy with how it feels. I wish there were a nullable if
statement syntax built-in.firstAttemptOrNull() ?: if? (someConditionMet()) secondAttemptOrNull()
would be sweet, and parallel features such as as?
Mark
03/02/2021, 2:02 AMJoel
03/02/2021, 2:03 AMorElse
in my codebase because it reads nicely, but I can't think of good syntax for the inverse that is meaningfully different from if
. i.e. thisThingIsValid.orElse { doSomething() }
Mark
03/02/2021, 2:05 AMifTrue
would be a much better name for my otherwiseIf
function of course!