TExcelTAD
Home › Scala › Scala Extension Methods

Scala Extension Methods

Sometimes you wish a type had one more method — String could have isPalindrome, Int could have isPrime. You cannot edit String, but with Scala 3 extension methods you can add methods to any existing type, and call them with normal dot syntax.

Defining an extension

scala · try it yourself
extension (s: String)
  def isPalindrome: Boolean =
    val clean = s.toLowerCase.filter(_.isLetter)
    clean == clean.reverse
  def words: List[String] = s.split("\\s+").toList.filter(_.nonEmpty)

@main def run(): Unit =
  println("Never odd or even".isPalindrome)
  println("Scala".isPalindrome)
  println("  the quick   brown fox ".words)
true
false
List(the, quick, brown, fox)

extension (s: String) names the receiver; inside the methods, s is the value the method was called on. Several methods can share one extension block.

Extensions on numbers

scala · try it yourself
extension (n: Int)
  def isPrime: Boolean =
    n > 1 && (2 to math.sqrt(n.toDouble).toInt).forall(n % _ != 0)
  def times(action: => Unit): Unit =
    for _ <- 1 to n do action
  def clampTo(lo: Int, hi: Int): Int = n.max(lo).min(hi)

@main def run(): Unit =
  println((1 to 30).filter(_.isPrime))
  3.times(print("hip "))
  println("hooray!")
  println(150.clampTo(0, 100))
Vector(2, 3, 5, 7, 11, 13, 17, 19, 23, 29)
hip hip hip hooray!
100

Generic extensions

Extensions can have type parameters, so one definition works for many types:

scala · try it yourself
extension [A](xs: List[A])
  def second: Option[A] = xs.drop(1).headOption
  def frequencies: Map[A, Int] = xs.groupMapReduce(identity)(_ => 1)(_ + _)

extension [A](a: A)
  def |>[B](f: A => B): B = f(a)   // a "pipe" operator

@main def run(): Unit =
  println(List(10, 20, 30).second)
  println(List("x").second)
  println(List("a", "b", "a").frequencies)
  val result = 5 |> (_ * 2) |> (_ + 1) |> (n => s"result=$n")
  println(result)
Some(20)
None
Map(a -> 2, b -> 1)
result=11

Extensions can define operators too, like the |> pipe above.

Extensions on your own types

Extensions are also useful for keeping a case class small and adding convenience methods next to the code that needs them:

scala · try it yourself
case class Money(cents: Long, currency: String)

extension (m: Money)
  def +(other: Money): Money =
    require(m.currency == other.currency, "currency mismatch")
    Money(m.cents + other.cents, m.currency)
  def show: String = f"${m.cents / 100.0}%.2f ${m.currency}"

extension (amount: Double)
  def eur: Money = Money(math.round(amount * 100), "EUR")

@main def run(): Unit =
  val total = 12.5.eur + 7.25.eur + 0.3.eur
  println(total)
  println(total.show)
Money(2005,EUR)
20.05 EUR

12.5.eur reads almost like natural language — a small domain-specific language built from ordinary extensions.

Scope and resolution

Extension methods must be in scope to be used: defined in the same file or package, imported, or placed in the companion object of the receiver type (or of a given instance — see the next chapters).

scala
object StringSyntax:
  extension (s: String) def shout: String = s.toUpperCase + "!"

import StringSyntax.*   // or: import StringSyntax.shout
"hi".shout              // "HI!"
Rule Detail
A real method always wins if String already had shout, the extension would be ignored
Must be visible define, import, or put in a companion/given
Can be called directly shout("hi") also works
Can't access private members extensions only see the public API of the receiver

Tip: Group related extensions in an object named like XxxSyntax or XxxOps, and import them where needed. That keeps it obvious where a "magic" method comes from.

Test yourself

Which syntax adds a method double to Int in Scala 3?

  1. implicit class double(n: Int)
  2. extension (n: Int) def double: Int = n * 2
  3. def Int.double = this * 2
  4. Int.prototype.double = ...

If a type already has a method foo and you add an extension foo, which is called by x.foo?

  1. The extension
  2. The type's own method
  3. Compile error: ambiguous
  4. Whichever was defined last

Can extension methods access private fields of the type they extend?

  1. Yes, always
  2. No, they only see the public API
  3. Only for case classes
  4. Only with @extension