How does Scala support 'Literal-based Custom Types'?

Instruction: Explain the concept of literal-based custom types in Scala and provide an example of their usage.

Context: This question probes the candidate's understanding of Scala's type system, specifically the creation and use of literal-based custom types to enhance type safety and readability.

Updated

In Scala 3, literal singleton types describe specific literal values, and a union can combine several accepted alternatives. This can make a small closed set of string values explicit in a method's input type.

type Role = "admin" | "editor" | "viewer"
def parseRole(raw: String): Either[String, Role] = raw match {
  case "admin" => Right("admin")
  case "editor" => Right("editor")
  case "viewer" => Right("viewer")
  case _ => Left("Unknown role")
}
def canEdit(role: Role): Boolean = role match {
  case "admin" | "editor" => true
  case "viewer" => false
}
@main def literalExample(): Unit = {
  assert(canEdit("editor"))
  assert(!canEdit("viewer"))
  assert(parseRole("admin").map(canEdit) == Right(true))
  assert(parseRole("owner").isLeft)
}

A call such as canEdit("owner") fails to compile. A runtime String is not automatically a Role; parse or validate it and return values with the narrower type rather than using an unchecked cast. Literal singleton types Scala 3 union types

This alias limits accepted values but does not create a nominal wrapper distinct from every other alias of the same literals. An enum or domain wrapper can be clearer when alternatives need behavior or must remain distinct from another concept. The canEdit example expresses a local policy decision for an already supplied role; it does not authenticate a person or establish that their claimed role is trustworthy.

Related Questions