dotty

A Scala function to determine whether a number is a prime number

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)

Scala 3: The Dotty if/then/else-if/else/end syntax

Table of Contents1 - Using `then` with if/else2 - Using `end if` with if/else3 - Closing a function with `end`4 - Discussion5 - Participate/contribute!6 - Attribution

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
Back to top

Using `then` with if/else

You can also use the then keyword after your if expressions, if you prefer:

A small Scala 2 project converted to Dotty

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).

Notes on using Dotty (Scala 3), SBT, and VS Code together

As a note to self, here are some ways to work with Dotty (Scala 3), SBT, and VS Code (Visual Studio Code).

Create a Dotty project:

sbt new lampepfl/dotty.g8

Launch VS Code inside that project directory, with Dotty support:

sbt launchIDE

Start SBT as usual:

sbt

Those notes are just a reminder for myself, but hopefully they’ll also help others work with Dotty, SBT, and VS Code.

Dotty (Scala 3) v20 for/do loop syntax

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:

Examples of converting Scala 2 code to Scala 3 with Dotty 0.20

Table of Contents1 - Significant indentation syntax with traits and classes2 - match expressions3 - for loops and if/else (and `do` and `then`)4 - try/catch syntax5 - A couple of braces not removed6 - More Dotty/Scala 3 changes

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 then and do keywords.