typestar

Extension methods in Scala

Adding methods to Int and String without owning either type.

// An extension block adds methods to a type you do not own. Inside
// it, the named parameter stands for the receiver.
extension (n: Int)
  def isEven: Boolean = n % 2 == 0
  def clampTo(limit: Int): Int = if n > limit then limit else n

extension (s: String)
  def shout: String = s.toUpperCase + "!"
  def initials: String = s.split(' ').map(_.take(1)).mkString(".")

// The calls read as though Int and String had always had these.
val evens: List[Int] = (1 to 10).toList.filter(_.isEven)
val capped: Int = 137.clampTo(100)
val cheer: String = "ship it".shout
val short: String = "ada byron lovelace".initials

// A one-argument extension can also be written infix, without a dot.
val trimmed: List[Int] = List(3, 40, 500).map(_ clampTo 99)

How it works

  1. extension (n: Int) names the receiver, then defines isEven and clampTo against it.
  2. extension (s: String) adds shout and initials the same way.
  3. The calls read as built in, from 137.clampTo(100) to the infix _ clampTo 99.

Keywords and builtins used here

The run, in numbers

Lines
18
Characters to type
736
Tokens
152
Three-star pace
70 tpm

At the three-star pace of 70 tokens a minute, this run takes about 130 seconds.

Type this snippet

Step 2 of 3 in Traits & extensions, step 23 of 27 in Language basics.

← Previous Next →

Extension methods in other languages