By   June 28, 2015

Compound Types in Scala
In the previous post we looked at Mixin composition with traits in Scala. This post is about a similar concept, called Compound types. The syntax is exactly the same, it uses the familiar with keyword. But there is some differences. Mixins are used to define types or instantiating them. On the other hand, compound types are used to specify dependencies as a sub-type of more than one types.

Example Scenario

Let’s consider a scenario where a person is asked to cover some distances. He can cover the given distance while walking or running. Apparently the person loves walking more than running. In order to keep things interesting for him, he can only walk in the patches of 5000 ft. He cannot walk more than three patches for covering the distance and has to run the remaining distance.

Distance more then maximum 3 walkable patches

Distance more then maximum 3 walkable patches

There can be no partial patches unless the given distance doesn’t cover a single patch. After the patch, the remaining distance must be covered while running.

Partial Patch

Partial Patch

Putting into Code

Scala provides with keyword to specify dependencies in terms of compound types. Here we are first determining, how many patches the person can walk before starting to run. In order to determine that we are first creating a sequence of numbers between 1 and 3. collect is selected because we need to filter and map.

Here we are filtering all those patches which can be covered while walking. If a distance lies in between two patch boundaries, it would be filtered by collect. We are then mapping the distance to cover the given patch.

Then we are getting the maximum patch. Any partial distance can be covered by walking.