🎓 A1Learner
🔍
0 of 45 lessons completed

Phantom Types

A phantom type is a type parameter that never appears in the fields of its class. It tags a value with extra meaning that exists only in the type.

A phantom tag marks a form as unvalidated

The form stores only text. The program prints the length of that text.

trait Unvalidated
trait Validated
class Form[S](val text: String)
@main def main(): Unit =
  val form = Form[Unvalidated]("hello")
  println(form.text.length)

A function changes the tag to validated

The conversion keeps the text unchanged. The program prints the length of the converted text.

trait Unvalidated
trait Validated
class Form[S](val text: String)
def validate(form: Form[Unvalidated]): Form[Validated] = Form[Validated](form.text)
@main def main(): Unit =
  val raw = Form[Unvalidated]("abcd")
  val checked = validate(raw)
  println(checked.text.length)

A gated function accepts only validated forms

The gated function needs a validated tag. The program doubles the length of the validated text.

trait Unvalidated
trait Validated
class Form[S](val text: String)
def validate(form: Form[Unvalidated]): Form[Validated] = Form[Validated](form.text)
def useValidated(form: Form[Validated]): Int = form.text.length * 2
@main def main(): Unit =
  val raw = Form[Unvalidated]("abcd")
  val checked = validate(raw)
  println(useValidated(checked))

Example

trait Unvalidated
trait Validated
class Form[S](val text: String)
def validate(form: Form[Unvalidated]): Form[Validated] = Form[Validated](form.text)
def useValidated(form: Form[Validated]): Int = form.text.length * 2
@main def main(): Unit =
  val raw = Form[Unvalidated]("hello")
  val checked = validate(raw)
  println(raw.text.length)
  println(useValidated(checked))

Key points

  • Phantom parameter: A phantom parameter is a type parameter unused by the fields.
  • Tag: A tag is a small empty trait used only as a marker in a type.
  • State: Two tags can mark two states, such as unvalidated and validated.
  • Conversion: A function can change the tag from one state to another while keeping the value.

In this example, the program builds an unvalidated form holding hello. It converts the form to validated without changing the text. It prints the raw length of 5 and the doubled validated length of 10.

Note

A phantom type differs from a normal type parameter because it changes the type without changing the stored data.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Scastie

Exercise

What does a phantom type parameter change?