0Pricing
Scala for Backend Engineering & Functional Programming · Lesson

Extension Methods

Add methods to types.

Adding methods to existing types

Extension methods let you add new methods to a type you do not own, like Int or String, without modifying its source. Scala 3 has clean syntax for this.

object Main:
  extension (x: Int)
    def squared: Int = x * x
  def main(args: Array[String]): Unit =
    println(5.squared)

The extension syntax

Write extension (param: Type) followed by one or more method definitions. Inside each method, the parameter refers to the receiver value.

object Main:
  extension (s: String)
    def shout: String = s.toUpperCase + "!"
  def main(args: Array[String]): Unit =
    println("hello".shout)

All lessons in this course

  1. Implicit Parameters
  2. Scala 3 given/using
  3. Implicit Conversions
  4. Extension Methods
← Back to Scala for Backend Engineering & Functional Programming