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




