As a brief note today, here’s an example of the Scala 3 “Dotty” if/then/else-if/else syntax, as used in a function:
def compare(a: Int, b: Int): Int = if a < b -1 else if a == b 0 else 1
Using `then` with if/else
You can also use the
then keyword after your
if expressions, if you prefer:
def compare(a: Int, b: Int): Int = if a < b then -1 else if a == b then 0 else 1
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`
compare function can also be written with an
end statement, if you prefer:
def compare(a: Int, b: Int): Int = if a < b -1 else if a == b 0 else 1 end compare
All of these examples currently compile with Dotty 0.21 in late January, 2020.
I share these examples because a couple of weeks ago I was having trouble getting a Dotty if/else-if/else expression to compile, but today all of these examples are working fine.
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.
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
help support my writing