Scala higher kind

Let's dive more into object oriented programming ideas but with a dash of functional programming.

The idea today is to go a bit further with trait and be able to describe behaviors of higher kinds. It is just a fancy terms to describe type that accept type as parameter, such as List[A], the A being the type accepted as parameter.

To create a generic trait that “target” type that take type(s) as parameter, the syntax is:

trait MyTrait[F[_]] 

The F[_] means that we are expecting a type F that take one type parameter as argument, the _.

Note that it is possible to target a type that takes two types as input with the following syntax: F[_, _]. You can imagine that it is possible to target type with more than two following the same logic.

When you use a parameterized type you do something like List[Int] so if you want to use the type itself you simply has to do Trait[List], not need to add anything after the List.

You also noticed that you can create your own type and it will behave the same way. Look at CounterT in our example. It takes one type as parameter so it can be used with our trait.

Reveal more information and clues
Load Exercise