Scala 3 Syntax, Migration & Experimental Features
Both brace and brace-less styles are valid; pick one per codebase (scalafmt can rewrite: rewrite.scala3.removeOptionalBraces = yes).
40.1 Optional braces (significant indentation)
Both brace and brace-less styles are valid; pick one per codebase (scalafmt can rewrite: rewrite.scala3.removeOptionalBraces = yes).
class Account(owner: String):
private var balance = 0
def deposit(amount: Int): Unit =
require(amount > 0)
balance += amount
def report(): String =
if balance > 1000 then
"rich"
else
"normal"
end Account // optional end marker40.2 Other Scala 3 syntax changes
import a.{B => C} import a.{B as C} implicit val implicit params implicit class trait A extends B with C extends B, C if (c) a else b if c then a else b for (x <- xs) yield for x <- xs yield while (c) { } sealed trait + case objects macros (scala.reflect) inline + quotes forSome existentials removed (use wildcards / type members) procedure syntax def f() { } Symbol literals 'sym
40.3 Migrating a codebase
Upgrade to the latest Scala 2.13 and fix warnings (-Xsource:3).
Replace Scala 2 macros/libraries lacking Scala 3 versions.
Use the Scala 3 Migration Mode (-source:3.0-migration -rewrite) and scalafix rules.
Scala 3 can depend on 2.13 artifacts (.cross(CrossVersion.for3Use2_13)) and vice versa (TASTy reader).
40.4 Experimental & recent features
Named tuples (3.7): (name = "Ann", age = 30).
Capture checking (import language.experimental.captureChecking): track capabilities/effects in types (File^), basis for safe direct-style effects.
into modifier for conversions, clause interleaving (def f[A](a: A)[B](b: B)), better-fors, modularity (tracked parameters), erased definitions, @publicInBinary.
Scala 3 LTS (3.3.x) for libraries; "Scala Next" for applications.
🧪 Part III Exercises
Implement a covariant immutable Stack[+A] with push[B >: A], pop, peek.
Write Show, Eq, and Monoid type classes with given instances for Int, String, List[A], Option[A].
Implement Functor and Monad for a custom Parser[A] type and write a JSON parser with for-comprehensions.
Use opaque types for UserId, Email, and Money with validated constructors.
Write a match type Flatten[T] that flattens nested tuples at the type level.
Write an inline/macro assertPositive(x) that fails compilation for negative literal arguments.
Derive a CsvEncoder[A] type class for case classes using Mirror.
Fetch 20 URLs concurrently with Future.traverse, then rewrite with Cats Effect parTraverseN(5) and timeouts.
Build a ZIO app with two ZLayer services (repo + notifier) and a test using in-memory layers.
Implement a bank account actor with Pekko Typed that rejects overdrafts and replies with balances.