ceylon/ceylon-spec — Issue #88: then and else operators
Author: gavinking
Created: 2011-12-07 02:14:29+00:00
State: open
Labels: request for feedback

So we don't currently have any form of conditional expression. C-like languages usually feature an operator like this:

x>0.0 ? x : 0.0

I personally use this quite often but it didn't seem to fit into the syntax of Ceylon because

1. we use `?` to indicate things to do with null, for example `Foo?`, `foo?.bar`, and `foo ? 0`, and
2. I've never met anyone who thinks it's a very natural syntax anyway.

Some languages, especially functional languages use something like this

if x>0.0 then x else 0.0

I find that quite reasonable, but taking into account regularity with C-style `if`, we would wind up with

if (x>0.0) x else 0.0

which I find pretty strange-looking and asymmetrical (note that Scala supports this syntax). I would prefer not to go down this path either.

Instead, I would like to propose the following:

1. a binary `then` operator, which accepts `Boolean` as its first argument, and any type `T` as its second argument, returning a value of type `T?` - it evaluates to `null` and short-circuits the second expression when the first argument is `false`, or evaluates to the second expression otherwise, and
2. a binary `else` operator that accepts any expression of type `T?` as its first argument, and an expression of type `T` as its second argument, behaving just like the `?` operator, but with a much lower precedence.

Both of these operators have a very low precedence, sitting between Layer 3 and Layer 4 in table 6.1 of the spec.

Now we can write stuff like:

1. ```x>0.0 then x else 0.0```
2. ```x>0.0 then x```
3. ```x else 0.0```

Currently we have no efficient way to write `x>0.0 then x`, and so I quite often find myself writing things like this:

if (x>0.0) {
return x;
}
else {
return null;
}

Which is pretty annoying to type, frankly. We do have a way to write `x else 0.0`, but the different precedence gives a little extra flexibility.

But most importantly, `x>0.0 then x else 0.0` reads extremely naturally.

What do you guys think?