kotlinif-statementlogic

Conditional branches of a 'when' expression in Kotlin


I need to write a Kotlin function that returns a result based on the outcome of a 'when' statement. For a trivial example, lets suppose my code looks like this:

fun combineThings(newThing:String, otherThing:String):String
{
    val thing1 = "abc"
    val thing2 = "def"
    val thing3 = "ghi"
    
    return when {
        newThing.length == 2 -> thing1 + thing2
        newThing.contains("qr") -> thing2 + thing3
        newThing.contains("123") -> thing1 + thing3
        newThing.length == 4 -> thing1 + thing2 + thing3
        else -> otherThing
    }
}

Simple enough. The problem is, I need a way to add more complicated logic. Suppose I wanted some of the branches to be evaluated ONLY when some other condition is true. So going back to the example, lets say I want to add logic to evaluate the second and third branches ONLY if otherThing == "foo". If otherThing != "foo", those branches get skipped and the when statement continues checking the rest of the branches.

In this trivial example, I could simply add an AND statement with the additional logic to each branch. In a real application however, that is going to be time consuming and prone to errors. I'm looking for some way to add a conditional block around the branches that need additional logic.

Is there any way to do what I want using a 'when' statement? If not, is there some other alternative to a bunch of if/else statements?


Solution

  • If you have a complicated conditional logic you can separate it from the when statement and its branches:

    val is2And3 = otherThing == "foo" && newThing.contains("qr")
    val is1And3 = otherThing == "foo" && newThing.contains("123")
    
    return when {
        newThing.length == 2 -> thing1 + thing2
        is2And3 -> thing2 + thing3
        is1And3 -> thing1 + thing3
        newThing.length == 4 -> thing1 + thing2 + thing3
        else -> otherThing
    }
    

    This way you have more freedom defining the conditions, and the when branches are still simple and easy to understand.