Extension methods
An extension method adds a member to a type without changing the type. The compiler turns price.euros into a call of a method that takes the price as its first argument, so an extension works on a type of the standard library, on a type of another library, and on a type parameter. Nothing is wrapped and nothing is allocated.
An extension on a type you own
One extension clause may hold several methods, and a method of it may be generic. Money gets a euro amount and a formatted price, List[A] gets second and penultimate for any element type, and String gets two case conversions:
extensions.scala
case class Money(cents: Long):
def +(other: Money): Money = Money(cents + other.cents)
extension (money: Money)
def euros: BigDecimal = BigDecimal(money.cents) / 100
def formatted: String = f"${money.euros}%.2f EUR"
extension [A](values: List[A])
def second: Option[A] = values.drop(1).headOption
def penultimate: Option[A] = values.dropRight(1).lastOption
extension (text: String)
def shout: String = text.toUpperCase + "!"
def quiet: String = text.toLowerCase
@main def extensions(): Unit =
val price = Money(1999)
println(price.euros)
println(price.formatted)
println(price + Money(1))
println(List(1, 2, 3).second)
println(List(1).second)
println(List(1, 2, 3).penultimate)
println("hello".shout)
println("HELLO".quiet)
scala-cli run --server=false extensions.scala
19.99
19.99 EUR
Money(2000)
Some(2)
None
Some(2)
HELLO!
hello
extension [A](values: List[A]) is a generic extension, and the A is inferred at the call from the list. price.euros reads like a method of Money and is resolved at compile time: no wrapper object exists at run time, and price.euros compiles to the same kind of call as euros(price). An extension cannot override a member: if the type already has a method of that name, the member wins.
The import an extension needs
An extension declared at the top level of the file is in scope everywhere below it. One declared inside an object is found only when the object or the method is imported, which is what makes a library of extensions possible:
with_import.scala
object TextOps:
extension (text: String)
def words: List[String] = text.split(" ").toList
def letters: Int = text.count(_.isLetter)
import TextOps.words
@main def with_import(): Unit =
println("a b c".words)
println("".words)
scala-cli run --server=false with_import.scala
List(a, b, c)
List()
import TextOps.words imports one extension method by its name, and import TextOps.* would bring the whole object. Without either, the call does not resolve, and the compiler says which name it could not find:
no_import.scala
object TextOps:
extension (text: String)
def words: List[String] = text.split(" ").toList
def letters: Int = text.count(_.isLetter)
@main def no_import(): Unit =
println("a b c".words)
mkdir -p out
scalac -color:never -d out no_import.scala 2>&1; echo "exit status: $?"
-- [E008] Not Found Error: no_import.scala:7:18 --------------------------------
7 | println("a b c".words)
| ^^^^^^^^^^^^^
| value words is not a member of String
1 error found
exit status: 1
value words is not a member of String is the error of a missing import, and it is the same error an extension that does not exist would give. That is the price of the feature: an extension is not visible from the type, only from a scope, and a reader who wonders where a method comes from looks at the imports of the file.
Related
- Operators are methods: the rule that makes price.euros a call.
- Opaque types: a new type whose operations are extensions on the representation.
- given and using: the other declaration an import brings into scope.
- Type classes: the pattern an extension is often written beside.
Article author: Arthur Isaev