🎓 A1Learner
🔍
0 of 45 lessons completed

Singleton Types

A singleton type is a type that allows exactly one value. A literal such as 1 or on can serve as its own type.

The type 1 allows only the value 1

The value is declared with type 1. The program multiplies it by 5.

@main def main(): Unit =
  val one: 1 = 1
  println(one * 5)

The type on allows only the string on

The value is declared with the "on" type. The program prints its length.

@main def main(): Unit =
  val mode: "on" = "on"
  println(mode.length)

A function can require the exact value 1

The function accepts only type 1. The program doubles that value through the function.

def doubleOne(x: 1): Int = x * 2
@main def main(): Unit =
  val one: 1 = 1
  println(doubleOne(one))

Example

def describe(c: 1, m: "on"): Int = c * 100 + m.length
@main def main(): Unit =
  val count: 1 = 1
  val mode: "on" = "on"
  println(describe(count, mode))

Key points

  • Literal type: A literal type is written as the literal value itself, such as 1.
  • Value: A value of a singleton type must equal that one literal.
  • Function: A function can accept a singleton type when it needs one exact value.
  • String literal: The type "on" allows only the string "on".

In this example, the program stores the exact values 1 and on. It multiplies the count by 100 to get 100. It adds the mode length of 2 to get 102.

Note

A singleton type differs from Int or String because it allows one value, not every value of that kind.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Scastie

Exercise

What values does the type 1 allow?