Scala 3 · 39 of 42

Extension methods

Remember “pimp my library” from the basic tour? In Scala 2, adding methods to an existing type meant wrapping it in an implicit class: a clever encoding, but you were really defining a wrapper class just to get one method.

Scala 3 says what it means: extension.

extension (i: Int)
  def squared = i * i

After this, 5.squared works anywhere the extension is visible (imported or in scope). Extensions can:

  • define several methods at once for the same receiver,
  • be generic (extension [T](list: List[T])),
  • take extra parameters, type bounds, and using clauses (they combine naturally with the contextual abstractions on the next page).

The old implicit class still compiles, so existing libraries keep working, but new Scala 3 code uses extension, and the standard library’s own enrichments are moving that way too.

//add methods to types you don't own
extension (i: Int)
  def squared = i * i
  def isEven = i % 2 == 0

println(5.squared)
println(4.isEven)

//works on any type, including other people's classes
extension (s: String)
  def vowels = s.count("aeiou".contains(_))
  def initials = s.split(" ").map(_.head).mkString(".")

println("scala rocks".vowels)
println("Martin Odersky".initials)

//extensions can take parameters and be generic
extension [T](list: List[T])
  def second: T = list.tail.head
  def penultimate: T = list.init.last

println(List(1, 2, 3, 4).second)
println(List(1, 2, 3, 4).penultimate)

//the Scala 2 way, for comparison (still works, but wordier):
implicit class RichIntOld(private val i: Int) {
  def cubed = i * i * i
}
println(2.cubed)

Contents

Scala basics

  1. Overview
  2. Scalculator
  3. Operators are methods
  4. Variables
  5. Final variables
  6. Printing values
  7. String interpolation
  8. String formatting
  9. Useful operations
  10. Method definition
  11. Method definition 2
  12. Method definition 3
  13. Anonymous functions
  14. Anonymous functions 2
  15. Return multiple values
  16. Declare multiple variables
  17. Assign multiple variables
  18. Loops using while
  19. Loops using for
  20. Loops without loops
  21. If
  22. Match as a switch
  23. Arrays
  24. Lists
  25. Sets
  26. Maps
  27. Mutable collections
  28. Collections: accessing elements
  29. Collections: concatenation
  30. Mutable collection operations
  31. Immutable collections with var
  32. Collections: useful methods
  33. Classes
  34. Classes, continued

What's new in Scala 3

  1. Scala 3: what changed
  2. Optional braces & new control syntax
  3. Top-level definitions & @main
  4. Enums & ADTs
  5. Extension methods
  6. given & using
  7. Union & intersection types
  8. Smaller niceties