Appendix A: Reading Scala 2
Scala 3 came out in 2021. A great deal of the Scala in production was written before that. Scala 2 code uses most of the same libraries, since they’re published for both versions. The older language is spelt differently, and one of its words, implicit, does several jobs that Scala 3 has given separate words, given, using and extension among them. This appendix shows one small program in both versions, so that you can read Scala 2 when you meet it.
The first version is written the way Scala 2.13 code usually is, 2.13 being the final version of Scala 2. Save it as desk.scala in a new directory called scala2. Its first line asks the scala command for a Scala 2 compiler, so it runs as it stands:
//> using scala 2.13.18
//> using jvm 25
package fullybooked
import java.time.{LocalTime => Time}
import scala.concurrent.duration._
sealed trait Status
object Status {
case object Requested extends Status
case object Confirmed extends Status
final case class Cancelled(reason: String) extends Status
}
final case class Party(name: String, size: Int)
trait Display[A] {
def text(value: A): String
}
object Display {
implicit val statusDisplay: Display[Status] = new Display[Status] {
def text(status: Status): String = status match {
case Status.Requested => "requested"
case Status.Confirmed => "confirmed"
case Status.Cancelled(reason) => s"cancelled ($reason)"
}
}
implicit def listDisplay[A](implicit each: Display[A]): Display[List[A]] =
new Display[List[A]] {
def text(values: List[A]): String = values.map(each.text).mkString(", ")
}
}
object syntax {
implicit class DisplayOps[A](value: A) {
def shown(implicit display: Display[A]): String = display.text(value)
}
}
class Tally {
private var count = 0
def add(size: Int): Unit = { count += size }
def total: Int = count
}
object Desk {
import syntax._
def longest[A: Display](values: List[A]): String =
values.map(implicitly[Display[A]].text).maxBy(_.length)
def covers(sizes: Int*): Int = {
val tally = new Tally
sizes.foreach(tally.add)
tally.total
}
def main(args: Array[String]): Unit = {
val parties = List(Party("Hughes", 4), Party("Mbeki", 8))
val statuses = List[Status](Status.Requested, Status.Cancelled("no deposit"))
val eight = Time.of(20, 0)
println(statuses.shown)
println(longest(statuses))
println(covers(parties.map(_.size): _*))
for (party <- parties if party.size > 4) {
println(s"${party.name} have the big table from $eight for ${90.minutes}")
}
}
}
$ scala run desk.scala
requested, cancelled (no deposit)
cancelled (no deposit)
12
Mbeki have the big table from 20:00 for 90 minutes
Here’s the same program in Scala 3. It goes in a second directory, scala3, under the same file name:
//> using scala 3.9.0
//> using jvm 25
package fullybooked
import java.time.LocalTime as Time
import scala.concurrent.duration.*
enum Status:
case Requested, Confirmed
case Cancelled(reason: String)
case class Party(name: String, size: Int)
trait Display[A]:
def text(value: A): String
object Display:
given Display[Status]:
def text(status: Status): String = status match
case Status.Requested => "requested"
case Status.Confirmed => "confirmed"
case Status.Cancelled(reason) => s"cancelled ($reason)"
given [A] => (each: Display[A]) => Display[List[A]]:
def text(values: List[A]): String = values.map(each.text).mkString(", ")
extension [A](value: A)(using display: Display[A])
def shown: String = display.text(value)
class Tally:
private var count = 0
def add(size: Int): Unit = count += size
def total: Int = count
def longest[A: Display](values: List[A]): String =
values.map(summon[Display[A]].text).maxBy(_.length)
def covers(sizes: Int*): Int =
val tally = Tally()
sizes.foreach(tally.add)
tally.total
@main def desk(): Unit =
val parties = List(Party("Hughes", 4), Party("Mbeki", 8))
val statuses = List[Status](Status.Requested, Status.Cancelled("no deposit"))
val eight = Time.of(20, 0)
println(statuses.shown)
println(longest(statuses))
println(covers(parties.map(_.size)*))
for party <- parties if party.size > 4 do
println(s"${party.name} have the big table from $eight for ${90.minutes}")
It prints the same four lines. The file is 52 lines long where the old one is 72.
A.1. Braces, new and main
In the old file the body of every class, trait and object is in braces, and so are the match and the longer method bodies. The party <- parties of the for is in parentheses and there’s no do. An if would be written if (free) seat else refuse, without then.
A class that isn’t a case class needs new to make an instance, as in Java, so covers says new Tally. The same word in new Display[Status] { ... } makes an instance of a trait on the spot, with the trait’s methods in the braces. In the Scala 3 file that’s a given Display[Status] with the method indented beneath it.
The program starts at a main method with Java’s signature, inside an object. The other common way was object Desk extends App, with the statements written straight into the object’s body. Scala 2 allowed only classes, traits and objects at the top level of a file, so longest and covers have to live inside Desk. Definitions meant for a whole package went in a package object.
A.2. An enum in five definitions
Scala 2 has no enum, so Status is a sealed trait, as Event was in chapter 8. Its cases sit in the companion object: a case object for each case without fields and a case class for the one with a reason. Both case classes in the file are marked final, which stops anything from extending them. Some Scala 2 codebases put final on every case class as a house rule.
A.3. The jobs of implicit
An implicit val or implicit def declares what Scala 3 calls a given. Scala 2 wanted names for them, so they’re called statusDisplay and listDisplay, though nothing in the file uses either name. The second has a parameter list of its own that starts with implicit. Scala 3 writes it as given [A] => (each: Display[A]) => Display[List[A]]: there’s a Display for a list whenever there’s one for its elements.
A parameter list that starts with implicit is a using clause: the compiler fills it in with a given of the right type. In longest, where the Display[A] has no name, implicitly[Display[A]] asks the compiler for it by hand. Scala 3’s word for that is summon.
An implicit class adds methods to a type that already exists, which is the job of extension in Scala 3. In the file, DisplayOps wraps any value so that shown can be called on it. Implicit classes are usually collected in an object called syntax or ops that has to be imported. Cats has an object of that kind behind the import cats.syntax.all.* we’ve been writing since chapter 11. The 90.minutes in main works because import scala.concurrent.duration._ brings in an implicit class for Int.
An implicit def with one ordinary parameter is an implicit conversion. The old file has none, but one such as implicit def toDuration(minutes: Int): FiniteDuration would let an Int be passed wherever a FiniteDuration is expected, and the call wouldn’t show it. When a value in old code seems to change type by itself, look for one of those in the imports. Scala 3 writes it as a given Conversion[Int, FiniteDuration] and warns when one is applied, unless the file that applies it has import scala.language.implicitConversions.
In Scala 2, import syntax._ brings in every implicit in the object along with everything else. In Scala 3 the * still brings in anything declared with implicit but leaves givens behind, and chapter 11’s import some.pkg.given fetches them.
A.4. Smaller differences
The Int* in the parameter list of covers means any number of Int arguments, like int... in Java. To pass a list where separate arguments are expected you mark it, with : _* in Scala 2 and * in Scala 3. The first import in the file gives LocalTime another name, Time.
| Scala 2 | Scala 3 |
|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
A.5. Scala 3 reads most of it
In the scala2 directory, change the first line of desk.scala to ask for 3.9.0 and run it again:
$ scala run desk.scala
[warn] ./desk.scala:67:41
[warn] The syntax `x: _*` is no longer supported for vararg splices; use `x*` instead
[warn] This construct can be rewritten automatically under -rewrite -source 3.4-migration.
[warn] println(covers(parties.map(_.size): _*))
[warn] ^
requested, cancelled (no deposit)
cancelled (no deposit)
12
Mbeki have the big table from 20:00 for 90 minutes
The one warning is about the : _* on line 67. Scala 3.9 accepts braces, implicit and everything in the left-hand column of the table above except the last row, with a warning of this kind for List[_] as well. That lets a team change compiler first and restyle the code later. The compiler does some of the restyling when it’s given -rewrite. I ran both of these on the file:
$ scala compile desk.scala -O -rewrite -O -source:3.4-migration
$ scala compile desk.scala -O -rewrite -O -indent
Each -O hands the option after it to the compiler. The first command is the one the warning suggests, and it changed only line 67, where : _* became *. The second took the braces off every class, trait, object, match and multi-line body. It left implicit, new, the parentheses of the for and the old imports as they were.
Macros, code that a library runs inside the compiler, usually take more work to move than syntax does. Scala 2 had its own way of writing them, which Scala 3 replaced. A library built on the old macros has to be swapped for its Scala 3 version, and macros a team wrote itself have to be written again. The Scala 3 migration guide is at https://docs.scala-lang.org/scala3/guides/migration/planning.html.