I was unsurprised but mildly disappointed that the...
# getting-started
r
I was unsurprised but mildly disappointed that the compiler couldn't cope with nested exhaustive `when`:
Copy code
enum class ExampleEnum {
  Val1, Val2, Val3
}

fun transform(exampleEnum: ExampleEnum): Int = when (exampleEnum) {
  ExampleEnum.Val1 -> 1
  else -> {
    val tmp = when (exampleEnum) {
      ExampleEnum.Val2 -> 2
      ExampleEnum.Val3 -> 3
    }
    tmp * 2
  }
}
Don't suppose there's an easy way around this other than to inline it:
Copy code
fun transform(exampleEnum: ExampleEnum): Int = when (exampleEnum) {
  ExampleEnum.Val1 -> 1
  ExampleEnum.Val2 -> 2 * 2
  ExampleEnum.Val3 -> 3 * 2
}
(Obviously in the real world the operation to apply to 2 & 3 is more complex!)
k
Different syntax, but related to https://youtrack.jetbrains.com/issue/KT-18950. I seem to remember reading that the general intention with such issues is to do it only in K2.
r
Thanks, good find!
e
@Rob Elliot You can try to do a nested sealed interface like this:
Copy code
sealed interface A {
  Val1 : A
  
  sealed interface B: A {
    Val 2: B
    Val 3: B
  }
}
In this case you will be able to divide Val 1 from Val2 and Val3, keeping all of them in one bigger sealed type A.
I found this trick pretty useful when I needed to divide a set of options in sealed interface in 2 groups keeping exhaustive when work.
r
Nice idea; in this particular case the instance needs to be looked up by name from an env var, so
Enum.valueOf
is more convenient than sealed interfaces, but thanks.
👍 1
d
@electrolobzik Doesn't you closely couple the model with its usage at a particular place? What if you need different when structure somewhere else?