Scala 3: Intro To Intersection Types

Shankar Shastri
2 min readOct 23, 2020

--

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

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

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:

MapReduce Using IntersectionTypes

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:

  1. Mapper[A, B] & Reducer[B, C] => Intersection type.
  2. List[A] => List on which map-reduce needs to be performed.
  3. mapFuncf => A Map function.
  4. 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 @mainannotation 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

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.

--

--