Just fooling around a little bit at the moment, here are several ways to write for/do blocks with the “significant indentation” style in Dotty (Scala 3) as of Dotty v20:
Not having a computer science background, I was curious about how to write a Scala function that would find a list of all prime numbers up until some maximum value I supply. I was aware of the Sieve of Eratosthenes, but I didn’t want to implement that, at least not today.
A Scala 3 (Dotty) function
What I ended up doing looks like other Scala prime number solutions you can find on the internet. To make things look a little different, I wrote the code using the current Scala 3 (Dotty) syntax, and the result looks like this:
def isPrime(i: Int): Boolean = if (i <= 1) false else if (i == 2) true else !(2 until i).exists(n => i % n == 0)
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:
If you want to see a somewhat larger example of Dotty source code than I’ve shown before, I just took a little time to convert a small Scala 2 project over to the new/current Dotty syntax (i.e., the Dotty syntax supported by the Dotty 0.21 release, circa January, 2020).
Scala 2.13 introduced two new “chaining operations” named
tap. Here’s a quick look at how they work, plus a little extra fun at the end.
Create a Dotty project:
sbt new lampepfl/dotty.g8
Launch VS Code inside that project directory, with Dotty support:
Start SBT as usual:
Those notes are just a reminder for myself, but hopefully they’ll also help others work with Dotty, SBT, and VS Code.
Here’s some source code that demonstrates a quiet, concise, and attractive new programming language I’d enjoy using:
With the Dotty compiler you can convert Scala 2 code to the new Scala 3 syntax, and with the Dotty 0.20.0-RC1 release on November 4, 2019, I thought I’d see how some of the conversions work. Almost all of the changes shown below have to do with the elimination of curly braces and the use of “significant indentation” syntax, but in one example I also show the
Here’s an example of Union Types in Scala 3 (Dotty). This image comes from this Martin Odersky video.