Scala Extension Methods
An extension method is a method written outside a type but called with dot syntax on its values. It adds new syntax for a type without changing the type itself.
An extension method is called with dot syntax
The extension block adds shout to String. Calling hi dot shout uppercases it and adds a mark.
extension (s: String)
def shout: String = s.toUpperCase + "!"
@main def main(): Unit =
println("hi".shout)An extension method can take an argument
The receiver is 10 and the argument is 5. The method adds them.
extension (n: Int)
def add(k: Int): Int = n + k
@main def main(): Unit =
println(10.add(5))An extension method can work on a list
The extension block adds doubled to lists of Int. It maps each item to twice itself.
extension (xs: List[Int])
def doubled: List[Int] = xs.map(_ * 2)
@main def main(): Unit =
println(List(1, 2, 3).doubled)Example
extension (s: String)
def shout: String = s.toUpperCase + "!"
extension (n: Int)
def doubled: Int = n * 2
@main def main(): Unit =
println("go".shout)
println(21.doubled)Key points
- Extension method: a method defined outside a type and called on values of that type.
- Receiver: the value before the dot is passed as the extension parameter.
- Extension block: an extension block names the receiver type and holds its new methods.
- Arguments: an extension method can take extra arguments after the receiver.
- Syntax only: an extension method adds call syntax. It does not add a member to the type.
In this example, the first extension block adds shout to String and the second adds doubled to Int. The call go dot shout prints GO with a mark. The call 21 dot doubled prints 42.
Note
extension methods work on any type, including types from the standard library.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Scastie
Exercise
What does "hi".shout print when shout uppercases the string and adds "!"?