Scala 3: Intro To Union Types
What Are Union Types
A union type is a type whose value will be of a single type out of multiple types.
Example:
type UnionType = Type1 | Type2 | ... | TypeN
How To Use Union Types In Scala 3
To explain union types, I have picked up a small example as shown below in the Gist:
As part of the above example, let's understand how we can create Option[T] using Union type. An Option[T] is a type whose type will be a Some[T] or None, based on the value. If the value t is null, then it will be None else it will be Some[T], where T is the type of t value.
The below type demonstrates how we create a union type Option[T] using union types. Here it signifies that Option[T] can either be Some[T] or None type.
type Option[T] = Some[T] | None
The toOption function takes a parameter t of type T, and has Option[T] as the return type. We can notice that based on the value t of T type, if t is null it will end up with None else Some[T] type.
To run the program, we use the @main
annotation on the method m. As part of the main function we are printing the results for toOption by passing null and a valid type. We can see that for null the result will be None and for the other, it will be Some[T].
References
- https://dotty.epfl.ch/docs/reference/new-types/union-types.html
- https://flow.org/en/docs/types/unions/
- https://www.typescriptlang.org/docs/handbook/unions-and-intersections.html#union-types
- https://en.wikipedia.org/wiki/Union_type
Wrapping it Up
If you have suggestions that I missed above, let me know in the responses!
If you found this helpful, click the 👏🏻 so more people will see it here on Medium.