liveBook · Manning

Eta expansion

As explained in Functional Programming in Scala, Second Edition

Eta expansion is the conversion of a method into a function value with equivalent behavior.

Eta expansion converts a method into a function value, allowing the method to be assigned to a val or passed where a function is required. In Scala, def defines a method; a function is a value. section 13.4.2

From method to function

A method such as def magnitude(o: Option[Int]): Int becomes a value with type Option[Int] => Int when assigned to val f = magnitude. Eta expansion also works for polymorphic methods, but ordinary inference chooses concrete type arguments: headOption becomes List[Any] => Option[Any].

When the type parameters must remain polymorphic, Scala requires explicit intent: [x] => (as: List[x]) => headOption(as). Scala 3 supports polymorphic function types directly; Scala 2 simulates them with a trait. section 13.4.2

This distinction enables generic interpreters such as runFree to accept a function that translates every F[x] into G[x], rather than a function fixed to one type.

How Functional Programming in Scala, Second Edition covers it

How deep it goes
Distinguishes methods from functions, demonstrates inferred types, and explains explicit polymorphic function types.
Examples
Uses magnitude, headOption, explicit polymorphic functions, and runFree translation functions.
What it assumes
Assumes basic Scala methods, values, function types, and type parameters while clarifying the method/function distinction.
What you can do after
Apply eta expansion by assigning methods to values and preserving polymorphism when constructing generic functions.
How it connects
Connects methods, functions, polymorphic methods, type parameters, natural transformations, and interpreters.

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.