The Scala 3 if/then/else-if/else/end syntax and examples

Scala FAQ: Can you show an example of the Scala 3 if-then-else-if syntax?

Scala 3 solution

Here’s an example of the Scala 3 if-then/else-if/else syntax, as used as the body of a method:

def compare(a: Int, b: Int): Int =
    if a < b then
        -1
    else if a == b then
        0
    else
        1

if/then/else

While I’m in the neighborhood, here’s an example of a one-line Scala 3 if/then/else expression. You can currently use either style that’s shown:

val a = if x < 0 then -x else x
val b = if (x < 0) then -x else x

Using `end if` with if/else

The if/else expression can also be closed with an end if, if you prefer:

def compare(a: Int, b: Int): Int =
    if a < b then
        -1
    else if a == b then
        0
    else
        1
    end if

Closing a function with `end`

The compare method/function can also be written with an end statement, if you prefer:

def compare(a: Int, b: Int): Int =
    if a < b then
        -1
    else if a == b then
        0
    else
        1
end compare

Discussion

All of these examples currently compile with Scala 3 (3.0.0-M2) on December 9, 2020.

Participate/contribute!

If you like or dislike the syntax shown, I encourage you to participate in the Dotty/Scala 3 process at contributors.scala-lang.org.

Update: I don’t see a SIP on this syntax at the list of Scala 3 SIPs, but I see a preference stated on this quiet control syntax page, and a discussion on this contributors.scala-lang.org page. If you’re interested in commenting on this syntax, I’d suggest commenting on that last link.

Attribution

I stumbled across this solution today while reading the Dotty 0.22 Optional Braces syntax page, where I saw this example:

def Run(ch: Char, n: Int): Run =
    if n <= MaxCached && ch == ' ' then
        spaces(n)
    else if n <= MaxCached && ch == '\t' then
        tabs(n)
    else
        new Run(ch, n)
end Run