🎓 A1Learner
🔍
0 of 45 lessons completed

Union Types

A union type is a type that allows a value to be one of several types. It is written with a vertical bar between the type names.

A union value can hold text

The value is declared with the union type. The program prints the text it holds.

type Code = String | Int
@main def main(): Unit =
  val code: Code = "A12"
  println(code)

The same union value can hold a number

The value is declared with the same union type. The program prints the number it holds.

type Code = String | Int
@main def main(): Unit =
  val code: Code = 42
  println(code)

A match separates the union cases

The match gives the length for text. It gives double the value for a number.

def describe(x: String | Int): Int =
  x match
    case s: String => s.length
    case i: Int => i * 2
@main def main(): Unit =
  println(describe("hi"))
  println(describe(7))

Example

type Code = String | Int
def describe(x: String | Int): Int =
  x match
    case s: String => s.length
    case i: Int => i * 2
@main def main(): Unit =
  val a: Code = "abcd"
  val b: Code = 10
  println(describe(a) + describe(b))

Key points

  • Union type: A union type lists the allowed types with a vertical bar.
  • Value: A value of a union type holds exactly one of the listed types at a time.
  • Match: A match can separate the union cases by checking each listed type.
  • Use: A union type fits a result that may be text or a number.

In this example, the program stores text of length 4 and the number 10. It converts the text to 4 and the number to 20. It adds the two results to get 24.

Note

A union type differs from a plain String type because it also allows an Int value.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Scastie

Exercise

What can a value of type String | Int hold?