🎓 A1Learner
🔍
0 of 48 lessons completed

Scala Type Aliases

A type alias is a new name for an existing type. The alias and the original type mean exactly the same thing to the compiler.

An alias for Int still adds like Int

UserId is an alias for Int. Adding one works exactly as it works for an Int.

type UserId = Int
@main def main(): Unit =
  val id: UserId = 42
  println(id + 1)

An alias can shorten a map type

Scores names a map from names to numbers. The map is used through its short name.

type Scores = Map[String, Int]
@main def main(): Unit =
  val scores: Scores = Map("Ana" -> 90, "Bo" -> 80)
  println(scores.getOrElse("Ana", 0))
  println(scores.size)

An alias value fits the original type

A UserId value fits into a plain Int value. The alias adds no barrier between the two names.

type UserId = Int
@main def main(): Unit =
  val user: UserId = 7
  val plain: Int = user
  println(plain)
  println(user + 3)

Example

type UserId = Int
type Team = List[String]
@main def main(): Unit =
  val id: UserId = 5
  val team: Team = List("Ana", "Bo", "Cy")
  println(id)
  println(team.length)
  println(team.mkString(", "))

Key points

  • New name: type UserId = Int gives the name UserId to the type Int.
  • Shorter code: an alias can shorten a long type such as Map[String, Int].
  • Same type: a value of the alias type can be used wherever the original type is expected.
  • No safety: an alias does not stop a plain Int from being used as a UserId.
  • Readability: aliases make code easier to read when the name says what the value means.

In this example, UserId names Int and Team names a list of strings, the id prints as a number, and the team prints its length and its members joined by commas.

Note

an alias adds no check at all, so it is a naming tool, not a safety tool.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Scastie

Exercise

What does a type alias give you?