Scala 3: Intro To Intersection Types
What Are Intersection Types
An intersection type is a type that combines multiple types into one type. It represents values that are of multiple types at the same time.
Example:
type IntersectionType = Type1 & Type2 & ... & TypeN
How To Use Intersection Types In Scala 3
To explain intersection types, I have picked up a small example as shown below in the Gist:
In the above example, we find trait Mapper[A, B] which has a method map that maps a given list List[A] to List[B] by applying function f: A => B .
Then we have trait Reducer[A, B] which has a method reduce that reduces a List[A] to B by applying function f:(B, B) => B .
We can create an intersection type MapReduce as shown below, which can be used to perform both map and reduce:
type MapReduce[A, B, C >: B] = Mapper[A, B] & Reducer[B, C]
The mapAndReduce method has the following parameters:
- Mapper[A, B] & Reducer[B, C] => Intersection type.
- List[A] => List on which map-reduce needs to be performed.
- mapFuncf => A Map function.
- reduceFuncf => A Reduce function.
We have also declared a case class MapperAndReducer which we will be using as a composite type in our mapAndReduce method.
To run the program, we use the @main
annotation on the method m. As we can notice, we are printing the result of mapAndReduce, by passing a map function that multiplies by 2 and reduces the result of the map by summing the mapped list.
References
- https://dotty.epfl.ch/docs/reference/new-types/intersection-types.html
- https://flow.org/en/docs/types/intersections/
- https://www.typescriptlang.org/docs/handbook/unions-and-intersections.html#intersection-types
- https://en.wikipedia.org/wiki/Intersection_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.