Kotlin's when with Pair - complicated contidions

632 views Asked by At

I have complicated bussiness logic conditions which I want to resolve via when statement. Let's say I have 3 enums Enum1, Enum2 and Enum3 and every has constans A,B,C,D... etc. And depending on value of Enum1 and Enum2 I need to determine list of Enum3 values. So I have function like this:

fun determineValues(enumPair: Pair<Enum1, Enum2>) : List<Enum3> {
   return when(enumPair){
       Enum1.A to Enum2.B -> listOf(Enum3.A, Enum3.B)
       Enum1.B to Enum2.C -> listOf(Enum3.A, Enum3.C)
       //..etc
    }
}

So far so good. However I have also condition when let's say for Enum1.C no matter what is in Enum2 I have to return some Enum3 values. I was trying to add to when conditions like this: Enum1.C to Any -> listOf(...), but it's not working. So I ended up with some ifs before when and it makes my code really less readable (I have a lot of business conditions like this)

So my question is: what is the simplest and cleanest way to do that?

1

There are 1 answers

0
Sweeper On

This feature of doing pattern matching in when does not exist yet. Even what you are doing now is not really pattern matching - you're just creating some temporary Pair objects and comparing equality. See this for a discussion about this. For now, the most concise way to do this that I can think of is:

    return when{
        enumPair == Enum1.A to Enum2.B -> listOf(Enum3.A, Enum3.B)
        enumPair == Enum1.B to Enum2.C -> listOf(Enum3.A, Enum3.C)
        enumPair.first == Enum1.C -> ...
        else -> ...
    }