How does Scala's 'Type Projection' work?
Instruction: Explain the concept of type projection in Scala and provide an example where it's useful.
Updated
A type projection such as SessionManager#Session refers to the member type across instances of a concrete outer type. A path-dependent type such as manager.Session instead keeps the relationship to one stable manager.
class SessionManager {
final class Session(val label: String)
def open(label: String): Session = new Session(label)
}
def anyLabel(session: SessionManager#Session): String = session.label
def ownedLabel(manager: SessionManager)
(session: manager.Session): String = session.label
@main def projectionExample(): Unit = {
val first = new SessionManager
val second = new SessionManager
assert(anyLabel(first.open("one")) == "one")
assert(anyLabel(second.open("two")) == "two")
assert(ownedLabel(first)(first.open("owned")) == "owned")
}
anyLabel intentionally accepts sessions from either manager. The projected type does not create a session without an enclosing instance. Passing a first-manager session to ownedLabel(second) fails to compile.
Version boundaries matter: Scala 2 allowed general projections on abstract types; Scala 3 permits projections only when the qualifying type is concrete. A declaration using an arbitrary type parameter T#Member is therefore not generally a valid Scala 3 replacement for an owner-dependent API. Scala 3 projection restriction
Use projection when accepting values from different owners is intentional. Keep a stable path when mixing them would be a programming error. Neither spelling verifies external session validity or provides an authorization check.
Related Questions
-
medium
-
medium
-
hard
-
hard
-
hard