Chapter 12: Higher Kinded Types
Last updated
Last updated
From the previous chapters, we get enough information regarding types and Kinds, in this chapter, we will be going to explore the next version of types or we can say that detailed abstraction of Kinds via Higher Kinded Types (HKT). As per our understanding, HKT provides a way to build functional data structures and I feel without HKT it is not possible to build a language with pure functional constructs(this is my opinion).
In the previous chapter, we figured out, Kinds are the more abstract way to define types and we are using some characters or in a symbolic way using * (asterisk) to explain the Kind of types.
Now the question is, what if parameterize constructor contains another parameterize constructor similar to function takes function as a parameter in functional programming. In general, we know if the function accepts a function as an argument or returns a function we called Higher-Order functions, similarly, if parameterize constructor which has another parameter constructor like Abstract[F[T]]
we called those types are Higher Kinded Types. As you can see, abstract type F itself contains parameterize constructor which is T. In this way, we can design complex Higher Kinded Types.
These terms function-within-function or Types-with-Types are sounds like inception
For experimenting with HKT, let’s create our own custom type:
Now we have a type of Abstract
that contains parameterize constructor F[T]
, which itself contains parameterize constructor [T]
.
Now, with the help of Kind command, lets trying to explain HKT:
According to the type, we have a slightly different symbolic explanation via :kind
command. As we know, our type parameter F has a type constructor with T, which explains as (* -> *)
. Here our inner constructors are wrapped via brackets and then -> *
denotes to the outer part. This is the complete reverse representation of Kinds, which we saw in the previous chapter, where we evaluate Kinds symbols from left to right, but in the case of HKT, the evaluation looks from right to left. Where left defined outer types and right defined for inner detailed types as we discussed for Abstract
type example.
Let’s take some advance example:
As you can see in this example, we have type EitherHKT
, where the left and the right types itself contains type constructor and while we explain via :kind
command, left side brackets shows inner types first then outer one. With the help of :kind
command, we can experiment any types which are available in our existing functional libraries like Cats, Scalaz, Zio, or more.
For more detailed explanations please go through the below articles: