Discuss the concept of path-dependent types in Scala.

Instruction: Explain path-dependent types with examples, including their use cases.

Context: This question assesses how a type can depend on a stable object path and how that relationship can prevent mixing values from different owners.

Updated

A path-dependent type can refer to a particular stable object's type member. Two instances of the same outer class can therefore have distinct inner types.

class Store {
  final class Key(val name: String)
  def key(name: String): Key = new Key(name)
}
def describe(owner: Store)(key: owner.Key): String = key.name

@main def dependentExample(): Unit = {
  val first = new Store
  val second = new Store
  val key = first.key("report")
  assert(describe(first)(key) == "report")
  val same: first.type = first
  assert(describe(same)(key) == "report")
  assert(describe(second)(second.key("other")) == "other")
}

Passing first's key to describe(second) fails to compile: first.Key is not second.Key. The parameter lists let the second parameter's type depend on the stable first parameter. A singleton-typed alias preserves the same path relationship. Inner classes and instance-dependent types

This is useful for APIs where a handle, token or model element belongs to a specific owner. Widening an API to accept keys from any owner loses that restriction. The type relationship is a static programming constraint, not an authorization check or proof that the key exists in an external database; those validations remain the application's responsibility.

Related Questions