Explain Scala's mechanism for literal-based custom types.
Instruction: Discuss how Scala supports the creation of literal-based custom types and their applications.
Updated
A literal type denotes a particular value, such as "v1" or 42. In Scala 3, a union of literal types can express a small accepted vocabulary. An ordinary string obtained at runtime still needs validation before it becomes that type.
type ApiVersion = "v1" | "v2"
def versionPath(version: ApiVersion): String = s"/api/$version"
def parseVersion(raw: String): Either[String, ApiVersion] = raw match {
case "v1" => Right("v1")
case "v2" => Right("v2")
case _ => Left("Supported versions are v1 and v2")
}
@main def literalVersionExample(): Unit = {
val one: "v1" = "v1"
assert(versionPath(one) == "/api/v1")
assert(parseVersion("v2").map(versionPath) == Right("/api/v2"))
assert(parseVersion("v3").isLeft)
}
Passing a literal "v3" directly to versionPath fails type checking. Widening a value to String loses the narrow guarantee even if the current value happens to be "v1"; the parser restores evidence by checking the runtime value. Literal aliases describe values, not new nominal identities. Scala literal types
Do not conflate literal types with arbitrary predicate validation. A Scala refinement type that narrows a member is not automatically a proof that a string is nonempty. A validated wrapper, opaque type with a checked constructor, or a refinement library can represent that rule, but dynamic input still requires a runtime check. Compile-time checks can reject only inputs for which the necessary evidence is available.
Use an enum when the domain needs named cases or richer behavior, and a validated wrapper for a larger constrained set. None of these mechanisms removes the need for authentication, external compatibility checks or handling invalid input.