Scala 3 Unions: Simulating Dynamic Typing with Union Types
This is an excerpt from the Scala Cookbook, 2nd Edition. This is Recipe 23.9, Simulating Dynamic Typing with Union Types.
Problem
When using Scala 3, you have a situation where it would be helpful if a value could represent one of several different types, without requiring those types to be part of a class hierarchy. Because the types aren’t part of a class hierarchy, you’re essentially declaring them in a dynamic way, even though Scala is a statically-typed language.
Solution
In Scala 3, a union type is a value that can be one of several different types. Union types can be used in several ways.
In one use, union types let us write functions where a parameter can potentially be one of several different types. For example, this function, which implements the Perl definition of true and false, takes a parameter that can be either an Int
or a String
: