Scala 3: Intro To Union Types

Shankar Shastri
2 min readOct 24, 2020

--

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

https://en.wikipedia.org/wiki/Union_(set_theory)

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:

Option[T] Using Union Types

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 @mainannotation 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

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.

--

--