scala 3

The Scala 3 “Dotty” procedure syntax

As a note to self, the Scala 3 “Dotty” procedure syntax is going to look like this:

def f() = { ... }
def f(): Unit = { ... }

This Scala 2 procedure syntax is being dropped:

def f() { ... }

You can find the official Dotty procedure syntax page at this link.

As for me, I’m adding this page right now because I noticed today that this procedure syntax (without the parentheses) also works with Dotty:

How to create a Scala 3 (Dotty) project with SBT alvin March 28, 2019 - 5:17pm

I can never remember how to create a Scala 3 (Dotty) project with SBT (in early 2019), so:

# create a new Dotty project
sbt new lampepfl/dotty.g8

# create a dotty project that cross compiles with scala 2
sbt new lampepfl/dotty-cross.g8

# start a dotty reply from within your sbt project
$ sbt

> console
scala> _

Here’s what an example interaction looks like — include SBT renaming my directory name to all lowercase, which brings me no joy:

Implicit methods/functions in Scala 2 and 3 (Dotty extension methods)

Table of Contents1 - Scala 2: Create the method in an implicit class2 - Scala 3 (Dotty): Adding methods to closed classes with extension methods3 - Discussion (Dotty syntax)4 - Where to put Dotty extension methods

Scala lets you add new methods to existing classes that you don’t have the source code for, i.e., classes like String, Int, etc. For instance, you can add a method named hello to the String class so you can write code like this:

"joe".hello

which yields output like this:

"Hello, Joe"

Admittedly that’s not the most exciting method in the world, but it demonstrates the end result: You can add methods to a closed class like String. Properly (tastefully) used, you can create some really nice APIs.

In this article I’ll show how you can create implicit methods (also known as extension methods) in Scala 2 and Scala 3 (Dotty).

The `f` string interpolator does not work with Dotty (Scala 3)

If you happen to be using Dotty (Scala 3) and find that the f string interpolator isn’t working, it’s a known bug. (It was implemented with a macro, and the old, experimental macro system has been dropped.) I’m writing this in January, 2019; I don’t know when it will work again. You can use the Java/Scala String.format method until it’s fixed:

val pi = scala.math.Pi
println( "%1.5f".format(pi) )