Reader small image

You're reading from  Kotlin Design Patterns and Best Practices - Second Edition

Product typeBook
Published inJan 2022
Reading LevelBeginner
PublisherPackt
ISBN-139781801815727
Edition2nd Edition
Languages
Right arrow
Author (1)
Alexey Soshin
Alexey Soshin
author image
Alexey Soshin

Alexey Soshin is a software architect with 15 years of experience in the industry. He started exploring Kotlin when Kotlin was still in beta, and since then has been a big enthusiast of the language. He's a conference speaker, published writer, and the author of a video course titled Pragmatic System Design.
Read more about Alexey Soshin

Right arrow

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...

lock icon
The rest of the page is locked
Previous PageNext Page
You have been reading a chapter from
Kotlin Design Patterns and Best Practices - Second Edition
Published in: Jan 2022Publisher: PacktISBN-13: 9781801815727

Author (1)

author image
Alexey Soshin

Alexey Soshin is a software architect with 15 years of experience in the industry. He started exploring Kotlin when Kotlin was still in beta, and since then has been a big enthusiast of the language. He's a conference speaker, published writer, and the author of a video course titled Pragmatic System Design.
Read more about Alexey Soshin