liveBook · Manning

Opaque type

As explained in Functional Programming in Scala, Second Edition

An opaque type is a Scala type whose representation is equivalent to an underlying type within its defining scope but abstract outside that scope.

An opaque type separates a useful abstraction from its representation. Inside its defining scope, it behaves like the underlying type; outside that scope, callers see an unrelated type. This preserves the efficiency of an alias without exposing its implementation. section 6.5 section 6.8

Modeling state actions

State[S, A] can represent a state computation as S => (A, S). Its defining scope can invoke the underlying function directly, while callers use run to execute it and apply to construct it. Unlike a plain alias, State cannot be confused with an ordinary function; unlike a case-class wrapper, it adds no runtime wrapping cost. section 6.5 section 6.8

opaque type State[S, +A] = S => (A, S)
 
object State:
  extension [S, A](underlying: State[S, A])
    def run(s: S): (A, S) = underlying(s)
 
  def apply[S, A](f: S => (A, S)): State[S, A] = f

Inspect the compact State definition, including its opaque representation, run extension method, and apply constructor. section 6.5

The pattern trades a small amount of conversion boilerplate for two benefits: callers receive a genuinely distinct type, and the implementation retains the performance characteristics of the underlying function. section 6.5

How Functional Programming in Scala, Second Edition covers it

How deep it goes
Defines scope behavior, conversions, and runtime tradeoffs, but defers detailed language specification.
Examples
Uses State[S, A] as S => (A, S) and Rand[A] as a specialized state alias.
What it assumes
Uses function types and type aliases as the starting point for introducing State.
What you can do after
Build it from scratch by defining State with apply and run while retaining encapsulation without wrapper overhead.
How it connects
Connects opaque types with type aliases, case classes, extension methods, State, and Rand.

Also explained in

Compare how 4 books explain opaque type →

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.