Book Image

Programming Kotlin

Book Image

Programming Kotlin

Overview of this book

Quickly learn the fundamentals of the Kotlin language and see it in action on the web. Easy to follow and covering the full set of programming features, this book will get you fluent in Kotlin for Android.
Table of Contents (20 chapters)
Programming Kotlin
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Customer Feedback
Preface

Sealed classes


A sealed class in Kotlin is an abstract class, which can be extended by subclasses defined as nested classes within the sealed class itself. In a way, this is a rather more powerful enumeration option. Just like Enum, a sealed class hierarchy contains a fixed set of possible choices. However, unlike Enum, where each option is represented by one instance, the derived classes of a sealed class can have many instances. Sealed classes are ideal for defining algebraic data types. Imagine you want to model a binary tree structure; you would do the following:

    sealed class IntBinaryTree {
      class EmptyNode : IntBinaryTree()
      class IntBinaryTreeNode(val left: IntBinaryTree, val value: Int, val right: IntBinaryTree) : IntBinaryTree()
    }

    …

    val tree = IntBinaryTree.IntBinaryTreeNode(
    IntBinaryTree.IntBinaryTreeNode(
      IntBinaryTree.EmptyNode(),
      1,
      IntBinaryTree.EmptyNode()),
     ...