liveBook · Manning

Extension

As explained in Functional Programming in Scala, Second Edition

An extension method is a method defined outside a type's original declaration that can be invoked with object-oriented syntax on values of that type.

An extension method is defined outside a type’s original declaration but called with object-oriented syntax on values of that type. It adds a method for a specific type without changing the type itself. section 3.4 section 3.6

For a generic tree, `size` can be written as either a method or a standalone function. Method syntax gives the call site `t.size` instead of `size(t)`, while preserving the same recursive pattern match. section 3.4

Adding `firstPositive` to `Tree[Int]`

A method declared directly on `Tree[A]` cannot specialize itself to integers. An extension method can: `extension (t: Tree[Int]) def firstPositive: Int = t match ...`. Its implementation receives the called tree as `t`, recursively checks the left branch, and searches the right branch when necessary. A call such as `myTree.firstPositive` works because the compiler searches for an extension when no regular method has that name. section 3.4

extension (t: Tree[Int]) def firstPositive: Int = t match
  case Leaf(i) => i
  case Branch(l, r) =>
    val lpos = l.firstPositive
    if lpos > 0 then lpos else r.firstPositive

Inspect the complete recursive extension-method definition for `Tree[Int]`, including its object-oriented recursive calls. section 3.4

How Functional Programming in Scala, Second Edition covers it

How deep it goes
Explains method-versus-function tradeoffs, type specialization, receiver binding, compiler lookup, and companion-object placement.
Examples
Uses recursive `Tree` operations: generic `size` and integer-specific `firstPositive`.
What it assumes
Assumes algebraic data types, recursive functions, and pattern matching on tree constructors.
What you can do after
Apply it via Scala extension syntax to add type-specific operations without editing the original type declaration.
How it connects
Connects extension methods to methods, standalone functions, pattern matching, algebraic data types, and companion objects.

Also explained in

Compare how 5 books explain extension →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Functional Programming in Scala, Second Edition. The section links point to the parts of the book it draws on.