Blaceless if expression as 'then' infix operator

The ‘then’ keyword as an infix operator for its braceless syntax version:

val text = if x > 0 then 'ok' else 'fail...' // current
val text = x > 0 then 'ok else 'fail...'    // suggestion

This would likely be hard to parse (both for the compiler and humans). What’s so bad about keeping the if? It’s one of the shortest keywords.

2 Likes

I imagine the goal is to look like C’s trinary expression: cond ? thenRes : elseRes.
IMO, redundant unreadable option. Scala already has too many ways of doing the same thing.

4 Likes

Worth comparing to match as infix, which is at least proposed for Scala 3.

To me, it doesn’t sound more outrageous than other ideas that came to pass.

I seem to recall there was a previous topic about implementing ternary conditional.

such constructs can be made easily in scala 3, even with nice error messages for unsupported cases (using different keywords of course). I don’t see any gain here.

import scala.util.NotGiven
import scala.annotation.implicitNotFound

extension (b:Boolean)
  def |?[T](a: => T)(
    using @implicitNotFound("argument of |? operator cannot be Unit. T == ${T}") 
    nu:NotGiven[Unit <:< T]
  ): T | Unit = if (b) a else ()

extension [T](arg: T | Unit)
  def |[E](or: => E): T | E = arg match {
    case _:Unit => or
    case a:T => a
  }

val x = 5
x >= 5 |? "biggerOrEq" | "smaller"
3 Likes