Extension Methods & Top-Level Definitions

Scala 2 equivalent: implicit class RichString(s: String) { def shout = ...

21.1 Extension methods

Scala 2 equivalent: implicit class RichString(s: String) { def shout = ... }.

extension (s: String)
  def shout: String = s.toUpperCase + "!"
  def words: List[String] = s.split("\\s+").toList

"hello world".shout      // "HELLO WORLD!"

extension [A](xs: List[A])
  def second: Option[A] = xs.drop(1).headOption

extension (n: Int)
  def times(f: => Unit): Unit = (1 to n).foreach(_ => f)

3.times(println("hi"))

21.2 Top-level definitions (Scala 3)

Scala 2 used package objects for this.

// file: utils.scala — no wrapping object needed
package myapp

val Version = "1.0"
def clamp(x: Int, lo: Int, hi: Int): Int = math.max(lo, math.min(hi, x))
type Id = Long