Union and Intersection Types in Scala 3

Photo by Denys Nevozhai on Unsplash

Scala 3 aka dotty comes with a lot of new types. Union, Intersection , Opaque etc. Let’s understand union and intersection types in detail.

Union types

A union type represents a type that has values of type or at a given time. A pattern match must be performed at the point of usage to extract the exact type.

This would not have been possible in Scala 2. We would have to create a super type for our types and then create the method with the super type.

Rules for Union types

  • Union types are commutative i.e is same as .
  • and are sub types of for all values of and
  • Co- Variance rules for Union types : Given a co-variant type then

Basically we can pass a and a to a method expecting a . This makes and a sub type of .

Also we can pass type where a is expected. This makes a sub type of . However the reverse is not possible as seen in line 24.

  • Contra-variance rules for Union types : Given a contra variant type C then and

Here, we see that we could pass a where a was required.

Intersection types

A intersection type represents a type that has values of type and at the same time.

At line 8 we are able to use both methods from intersection type i.e contains the functionality of both Semigroup and Indentity types. The intersection type will also act as a type restriction, so we need to mix in both traits if we are to use this method properly.

Rules for Intersection types

  • Intersection types are commutative i.e is same as .
  • Given any types and , is a sub type for both and
  • Co- Variance rules for Intersection types : Given a co-variant type then

Here, we see that we can provide an when we need a or a . This also leads us to the fact that when we need an we can provide a .

  • Given a contra-variant type a is a sub type of

What happens here is that a instance which knows how to print can be passed when we need a . This is exactly what is done is line 15.

  • what happens the two intersected types share a method signature except the returned types?

Here both and types have a method called with the same signature but different return types. An intersection type of these two upon calling the method must return both an and a . The only type that can do that is an intersection i.e .

Conclusion

We explored Union and Intersection types in Scala 3 and checked how these types work with variance rules in Scala. Checkout the official dotty docs for further reading

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store