The penultimate conditional syntax

24 points by fanf


matklad

I am huge fan of Kotlin’s low-tech solution, which is a combination of three things.

  1. Multiway if:
when {
   x > 0 -> "postive"
   x == 0 -> "zero"
   x < 0 -> "negative"
}

(seriously, every language should have multiway if! if else chains are horribly unreadable, as they don’t visually separate conditions from actions, but complex multiway ifs is exactly where you want maximum readability)

  1. is pattern-matching expression, which combines with flow sensitive typing:
if (animal is Cat && animal.meow().isLoud())

I think is can be straightforwardly extended to unpacking, rather than just narrowing types:

if (animal is Cat(cat) && cat.meow().isLoud())
  1. Exhaustive matching which is syntactically similar to the combination of the two:
when (animal) {
  is Cat -> "meow"
  is Fox -> "???"
}

What is cool is that you can easily upgrade exhaustive match to an arbitrary complex condition:

when {
  animal is Cat && animal.isFerral -> "deadly silence"
  animal is Cat -> "meow"
  animal is Fox -> "???"
}

You have to bind scrutinee to a variable and then repeat it in conditions, but that’s wasn’t a huge pain in practice (though this part might depend on type narrowing semantics, where you generally need fewer names to being with). My only two complains about Kotlin’s conditionals were that default formatting eats two levels of indentation, and that often binary when managed to look better than an if!

if (condition) 
  trueBranch
else 
  falseBranch

vs

when {
  condition -> trueBranch
  else -> falseBranch
}

which really is more of a complaint about if :D

Though, I was surprised to learn that there’s a KEEP to add guards to Kotlin: https://github.com/Kotlin/KEEP/blob/guards/proposals/guards.md

Like, it is a feature that you don’t need guards because the desired semantics falls out naturally from the combination of other features! But I haven’t touched Kotlin for a long while! :0)

Not sure how I feel about UCS or PUCS! Definitely an important problem to solve, but somehow the solution doesn’t immediately appeal to me.