If / then / else with captured values


#1

I’m trying to avoid some sideways programming around cases where I need to evaluate something, do a conditional on that evaluation, and use the result. Particularly in the case of regex.

val resultA = regexA.matchEntire(str)
if (resultA != null) {
    // Use result A
} else {
    val resultB = regexB.matchEntire(str)
    if (resultB != null) {
        // Use result B
    } else {
       ...
    }
}

In JS you can capture a value inside a conditional, but Kotlin you can’t, so I’m wondering what’s the idiomatic way to do this in Kotlin?


#2
regexA.matchEntire(str)?.also { match ->
    // Use result A
} ?: regexB.matchEntire(str)?.also { match ->
    // Use result B
} ?: run {
    // Else case
}

This is what I came up with, but open to suggestions.


#3

This seems to be the most elegant way to me. At least if you want to keep a hold of the match result. You could try when and putting code in the comparison (with apply/run), but that gets ugly quickly.