Implementing Algebraic Data Types
Algebraic Data Types, or ATDs for short, is a concept from functional programming and is very similar to the Composite design pattern we discussed in Chapter 3, Understanding Structural Patterns.
To understand how ADTs work and what their benefits are, let's discuss how we can implement a simple binary tree in Kotlin.
First, let's declare an interface for our tree. Since a tree data structure can contain any type of data, we can parameterize it with a type (T
):
sealed interface Tree<out T>
The type is marked with an out
keyword, which means that this type is covariant. If you aren't familiar with this term, we'll cover it later, while implementing the interface.
The opposite of a covariant is a contravariant. Contravariant types should be marked using the in
keyword.
We can also mark this interface with a sealed
keyword. We saw this keyword applied to regular classes in Chapter 4, Getting Familiar with Behavioral...