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
- Implicit Parameters
- Scala 3 given/using
- Implicit Conversions
- Extension Methods