Discuss the use cases and limitations of Scala's type alias feature.
Instruction: Provide examples of when and why to use type aliases, and any limitations they might have.
Updated
A type alias gives an existing type a descriptive name. It is useful for repeated nested signatures and domain vocabulary, but a normal alias remains equal to its underlying type.
type Matrix = Map[String, Map[String, Vector[Double]]]
type UserID = String
object Accounts {
opaque type AccountID = String
def parse(raw: String): Option[AccountID] =
Option(raw).filter(_.nonEmpty)
def text(id: AccountID): String = id
}
@main def aliasExample(): Unit = {
val matrix: Matrix = Map("row" -> Map("col" -> Vector(1.0, 2.0)))
val id: UserID = "12345"
val ordinary: String = id
assert(matrix("row")("col").sum == 3.0 && ordinary == "12345")
assert(Accounts.parse("").isEmpty)
assert(Accounts.parse("A-7").map(Accounts.text) == Some("A-7"))
}
UserID does not stop another string from being passed where a user ID is expected. Matrix does not establish rectangular shape, numeric validity or safe lookup of absent keys. Changing an alias's underlying type can still break callers: centralizing its spelling is not a compatibility guarantee.
The Scala 3 opaque type demonstrates a different boundary. Inside Accounts, its representation is known; outside, an arbitrary String cannot be assigned to Accounts.AccountID. The constructor above checks only non-null and nonempty input; real identifier rules would need explicit validation. Opaque aliases do not automatically validate data or make unsafe casts safe. Opaque type scope
Use a normal alias for readability, an opaque type when representation hiding and distinct static identity are required, or a wrapper case class when a separate runtime object and its domain API are appropriate. Keep names meaningful and avoid aliases that conceal important ordering, mutability or error behavior.