🎓 A1Learner
🔍
0 of 45 lessons completed

Match Types

A match type is a type that computes another type by matching on a type. It chooses a result type from cases, like a match chooses a value.

A match type computes Char from String

The String case gives Char. The program stores a Char in a value of the computed type.

type Elem[X] = X match
  case String => Char
  case Array[t] => t
  case Iterable[t] => t
@main def main(): Unit =
  val first: Elem[String] = 'a'
  println(first)

A match type computes Int from an array of Int

The array case gives the item type. The program stores an Int in a value of the computed type.

type Elem[X] = X match
  case String => Char
  case Array[t] => t
  case Iterable[t] => t
@main def main(): Unit =
  val n: Elem[Array[Int]] = 7
  println(n)

A match type computes Double from a list of Double

The collection case gives the item type. The program stores a Double in a value of the computed type.

type Elem[X] = X match
  case String => Char
  case Array[t] => t
  case Iterable[t] => t
@main def main(): Unit =
  val d: Elem[List[Double]] = 2.5
  println(d)

Example

type Elem[X] = X match
  case String => Char
  case Array[t] => t
  case Iterable[t] => t
@main def main(): Unit =
  val a: Elem[String] = 'z'
  val b: Elem[Array[Int]] = 9
  val c: Elem[List[Double]] = 1.5
  println(a)
  println(b)
  println(c)

Key points

  • Match type: A match type is declared by writing match after the type being matched.
  • Case: Each case pairs a pattern type with a result type.
  • String case: A case for String can give Char as its result type.
  • Collection case: A case for a collection can give the type of its items.

In this example, the program stores a Char, an Int, and a Double. Each value uses the type computed by its match case. It prints the three values in order.

Note

A match type differs from a value match because it chooses a type before the program runs.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Scastie

Exercise

What does Elem[String] give in the lesson example?