Scala 3 Highlights

Notes on what's coming in Scala 3.

These are the notes for my talk at The Chicago-Area Scala Enthusiasts (CASE), Nov. 19, with more recent updates. Some of these code examples are in my running series of blog posts on Scala 3. Most are adapted from the Code examples for Programming Scala, Third Edition with a few “borrowed” from the Dotty documentation.

For More Information

Programming Scala 3rd Edition Cover

General Comments

Some features are transitional; you can mix old with new in 3.0, but subsequent releases will start deprecating and warning about deprecated features.

To get started, an EPFL SBT plugin brings Dotty/Scala 3 support to SBT:

New Syntax

Blog post

You can now use significant indentation (“braceless”), like Python or Haskell, rather than curly braces. You can also mix and match, or use a compiler flag to force one or the other (see below).

Types

Methods

Partial Functions

gist

Match Expressions

But “Custom Controls” Don’t Work (yet…)

Create a custom loop “control”:

There is an experimental compiler flag -Yindent-colons that enables this to work, but there are details to work out before it’s considered fully supported (Scala 3.1??).

New Control Syntax

There are also new options for control syntax, but whether or not you use them is controlled by compiler flags:

Contextual Abstractions

We begin the migration aware from the implicit mechanism to constructs that more clearly indicate the intent.

Extension Methods Instead of Implicit Conversions.

Blog post

Remember the ArrowAssoc implicit conversion??

It’s much simpler and more direct to use an extension method. The following example shows how to define a ~> method on any type A. The @targetName annotation defines the name generated in byte code for the method (but this is only visible to other languages, like Java, not Scala code!).

NOTE: Use alpha instead of targetName for Scala 3.0.0-M1.

Extension methods are part of a new syntax for type classes, which I’ll cover in a moment.

NOTE: If you also defined an arrow2 method, it would collide with the target name given for ~>.

There are still cases where implicit conversions are useful, e.g., allow users to specify Double values that are converted to domain types, like Dollars and Percentage:

Note the new given syntax. This replaces implicit val/def, in general.

Note the name that is synthesized for the first given instance if you don’t explicitly provide a name, given_Conversion_Double_Dollars.

Note that as keyword when the second given instance is named.

By the way, the first definition is shorthand for this:

given Conversion[Double,Dollars]:
  def apply(d: Double): Dollars = Dollars(d)

Even when a given is anonymous, you can use summon[Conversion[Double,Dollars]] to bind to it. The new method summon is identical to implicitly; a new name for a newly-branded concept:

scala> summon[Conversion[Double,Dollars]]
val res68: Conversion[Double, Dollars] = <function1>

Maybe you already noticed that Conversion looks shockingly similar to A => B.

New Type Classes

Blog post

The syntax combines traits (to define the abstraction), regular and extension methods, and given instances (for type class instances):

Notice which members are extensions and which ones aren’t! The extension methods will be instance members and the others will be the equivalent of companion object members; we only need one unit per type T.

Create two monoid instances:

Try them out:

We can actual define the monoid instance for all T for which Numeric[T] exists:

Now we see our first example of a using clause, the successor to an implicit parameter list.

Using Clauses

Blog post

We just saw a using clause. They can be anonymous, too. Here’s an (unnecessary ;) wrapper around Seq for sorting them:

I passed the implicit/given values explicitly to Seq.sortBy for illustration purposes, but of course I could have passed them implicitly (usingly?).

Given Imports

Blog post

To allow use of _ for imports, but not pull in all givens when you don’t want them:

In Scala 3.0, _ will still import everything, for backwards compatibility, but Scala 3.1 will begin transitioning to this behavior.

NOTE: “non-givens” should be called takes IMHO… If you grew up with the King James Bible (1611) in your Baptist church like I did, they would be giveth and taketh

Infix Operator Notation

Because people abuse operator notation, Scala is migrating towards disallowing it, by default, unless:

  1. The method name uses only “operator characters”.
  2. The method is annotated with @scala.annotation.infix.
  3. Usage is followed by a curly brace.
  4. Back ticks are used:

In our previous example:

scala> "2" combine ("3" combine "4")
     |
1 |"2" combine ("3" combine "4")
  |                 ^^^^^^^
  |Alphanumeric method combine is not declared @infix; it should not be used as infix operator.
  |The operation can be rewritten automatically to `combine` under -deprecation -rewrite.
  |Or rewrite to method syntax .combine(...) manually.
1 |"2" combine ("3" combine "4")
  |    ^^^^^^^
  |Alphanumeric method combine is not declared @infix; it should not be used as infix operator.
  |The operation can be rewritten automatically to `combine` under -deprecation -rewrite.
  |Or rewrite to method syntax .combine(...) manually.

scala> "2" combine { "3" combine { "4" } }
val res0: String = 234

scala> "2" `combine` ("3" `combine` "4")
val res1: String = 234

Or, mark combine with infix, then you can use "2" combine ("3" combine "4"):

Note: I had to redefine the previous monoid instances with this new definition to add infix to each concrete definition of combine.

Now combine can be used with infix notation as an alternative to <+>:

scala> "2" combine ("3" combine "4")
val res2: String = 234

Easier Enums

(No blog post yet!)

I can never remember the Scala 2 syntax for enums. Now I have an even easier syntax to forget!

Adapted from Dotty docs:

NOTE: As commented by Seth Tisue during the CASE meeting, Scala 3 uses the Scala 2 library unchanged, so types like Option won’t be changed to enums until some future release.

Type Madness!! (Or Sanity…)

Opaque Type Aliases

blog post

Opaque type aliases have advantages and disadvantages compared to value classes. Example adapted from the Dotty docs:

In action:

Value classes still have a few advantages. They are real classes, so you can customize the equals and toString methods for them and you can pattern match on them (although this causes boxing to be required). Opaque type aliases don’t provide these benefits, but they prevent occurrences of boxing. Finally, the JDK will eventually have its own form of value classes (the Valhalla project), in which case a Scala representation will be desirable.

Open Classes

Also in this blog post

No more ad-hoc extensions of concrete types (unless you want ‘em):

(Wouldn’t make sense for abstract classes and traits, which must be extended to become concrete…)

What if a type isn’t open, but you want to subclass it in a test to stub methods (i.e., make a test double)? Use import scala.language.adhocExtensions in the test file. This is the advantage over declaring the type final, which provides no mechanism for this sort of “exceptional” extension.

Intersection and Union Types

blog post (Note: I used different examples in the post than the ones below. The post also goes into more details about algebraic properties of these types.)

Intersection Types

Intersection types work much like with for trait mixins:

trait Resettable:
  override def toString:String = "Resettable:"+super.toString
  def reset(): Unit

trait Growable[T]:
  override def toString:String = "Growable:"+super.toString
  def add(t: T): Unit

def f(x: Resettable & Growable[String]): String = 
  x.reset()
  x.add("first")
  x.add("second")
  x.toString

Note how the argument x for f is declared.

I find it a little confusing, but you have to actually instantiate these types using with:

case class RG(var str: String = "") extends Resettable with Growable[String]:
  override def toString:String = s"RG(str=$str):"+super.toString
  def reset(): Unit = str = ""
  def add(s: String): Unit = str = str + s

case class GR(var str: String = "") extends Growable[String] with Resettable:
  override def toString:String = s"GR(str=$str):"+super.toString
  def reset(): Unit = str = ""
  def add(s: String): Unit = str = str + s

I declared two types, one with Resettable & Growable[String] and the other with Growable[String] & Resettable. They are considered the same type by f. In other words, they commute, just like the intersection operation in set theory. In contrast, Scala 2 treated Resettable with Growable[String] and Growable[String] with Resettable as different types.

Let’s try them!

scala> val rg = new RG
     | val gr = new GR
     |
val rg: RG = RG(str=):Growable:Resettable:rs$line$16$RG@173b3581
val gr: GR = GR(str=):Resettable:Growable:rs$line$16$GR@367164f5

scala> f(rg)     // Both can be passed to `f`, showing commutativity.
     | f(gr)     // But toString shows different ordering of the "supers"!
     |
val res0: String = RG(str=firstsecond):Growable:Resettable:rs$line$16$RG@697f3db1
val res1: String = GR(str=firstsecond):Resettable:Growable:rs$line$16$GR@b3cd3f1e

Note that we got Growable:Resettable vs. Resettable:Growable.

(The :rs$line$... comes from calling super.toString on the object wrapping the code in the REPL! Just ignore it…)

Linearization is still used to decide which of an overridden method gets called when you use super.method(...). In this example, super.toString returns different results for Resettable & Growable[String] vs. Growable[String] & Resettable, even though those two types are considered equivalent from the type-checking perspective! Note which trait’s toString got called first for each case. (Hint: linearization is basically right to left ordering.)

WARNING: While A & B and B & A are considered equivalent types, the behaviors of overridden methods may be different, due to linearization.

Union Types

Union types could replace Either[A,B], but they aren’t limited to two nested types. Consider this pseudo DB query example:

case class User(name: String, password: String)

def getUser(id: String, dbc: DBConnection): String | User | Seq[User] = 
  try
    val results = dbc.query(s"SELECT * FROM users WHERE id = $id")
    results.size match 
      case 0 => s"No records found for id = $id"
      case 1 => results.head.as[User]
      case _ => results.map(_.as[User])
  catch 
    case dbe: DBException => dbe.getMessage

getUser(dbc) match
  case message: String => error(message)
  case User(name, password) => ...
  case seq: Seq[User] => ...

Note how pattern matching is necessary to determine what was returned from getUser. Compared to Either, you give up the useful operations like map, flatMap, etc. as alternatives to pattern matching like this.

Speaking of match expressions…

Match Types

This can be a bit “quirky”, but it’s a cool feature. (Example adapted from the Dotty docs):

type Elem[X] = X match
  case String => Char
  case Array[t] => t
  case IterableOnce[t] => t
  case ? => X

val char: Elem[String] = 'c'
val doub: Elem[List[Double]] = 1.0
val tupl: Elem[Option[(Int,Double)]] = (1, 2.0)

val bad1: Elem[List[Double]] = "1.0"        // ERROR
val bad2: Elem[List[Double]] = (1.0, 2.0)   // ERROR

summon[Elem[String] =:= Char]  // ...: Char =:= Char = generalized constraint
summon[Elem[List[Int]] =:= Int]
summon[Elem[Nil.type] =:= Nothing]
summon[Elem[Array[Float]] =:= Float]
summon[Elem[Option[String]] =:= String]
summon[Elem[Some[String]] =:= String]
summon[Elem[None.type] =:= Nothing]
summon[Elem[Float] =:= Float]
summon[Elem[Option[List[Long]]] =:= Long]   // ERROR

The last one fails because our match type doesn’t handle nesting beyond one level. This is possible; the type can be recursive!

Migration

The book’s code examples use the flag -source 3.1 to force deprecation warnings for older constructs. The default, -source 3.0, is more forgiving.

Flags to control syntax preferences:

  • -indent: Allow significant indentation.
  • -noindent: Require classical {…} syntax, indentation is not significant.
  • -new-syntax: Require then in conditional expressions.
  • -old-syntax: Require (...) around conditions.

Flags to help migration:

  • -language:Scala2: Compile Scala 2 code, highlight what needs updating.
  • -migration: Emit warning and location for migration issues from Scala 2.
  • -rewrite: Attempt to fix code automatically.

Other Things of Note…

  • Trait parameters
  • Completely new macro system
  • Transparent traits
  • export clauses
  • type lambdas: type F = [A] =>> FooBar[A]
  • kind polymorphism: generalize over A, F[A], G[A,B], …
  • dependent function types (we’ve had dependent method types)
  • New types like Tuple, EmptyTuple (and tuple operations)
  • Explicit nulls: def callJava(...): String | Null
  • Safe initialization
  • @main methods: instead of object Foo { def main():Unit = ??? } boilerplate
  • No more 22-arity limits on tuples and functions
  • … and lots of smaller refinements