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
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
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:
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:
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).
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
XxxSyntaxorXxxOps, 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?
implicit class double(n: Int)extension (n: Int) def double: Int = n * 2def Int.double = this * 2Int.prototype.double = ...
If a type already has a method foo and you add an extension foo, which is called by x.foo?
- The extension
- The type's own method
- Compile error: ambiguous
- Whichever was defined last
Can extension methods access private fields of the type they extend?
- Yes, always
- No, they only see the public API
- Only for case classes
- Only with
@extension