Book Image

Kotlin Programming Cookbook

By : Aanand Shekhar Roy, Rashi Karanpuria
Book Image

Kotlin Programming Cookbook

By: Aanand Shekhar Roy, Rashi Karanpuria

Overview of this book

The Android team has announced first-class support for Kotlin 1.1. This acts as an added boost to the language and more and more developers are now looking at Kotlin for their application development. This recipe-based book will be your guide to learning the Kotlin programming language. The recipes in this book build from simple language concepts to more complex applications of the language. After the fundamentals of the language, you will learn how to apply the object-oriented programming features of Kotlin 1.1. Programming with Lambdas will show you how to use the functional power of Kotlin. This book has recipes that will get you started with Android programming with Kotlin 1.1, providing quick solutions to common problems encountered during Android app development. You will also be taken through recipes that will teach you microservice and concurrent programming with Kotlin. Going forward, you will learn to test and secure your applications with Kotlin. Finally, this book supplies recipes that will help you migrate your Java code to Kotlin and will help ensure that it's interoperable with Java.
Table of Contents (21 chapters)
Title Page
Copyright and Credits
Packt Upsell
Contributors
Preface
Index

Restricting class hierarchies


In this recipe, we will learn how to restrict the class hierarchies in Kotlin. Before we move ahead, let's understand why this is a cause worth spending our time on.

Getting ready

I'll be using Android Studio to run the code described in this recipe.

How to do it…

When we are sure that a value or a class can have only a limited set of types or number of subclasses, that's when we try to restrict class hierarchy. Yes, this might sound like an enum class but, actually, it's much more than that. Enum constant exists only as a single instance, whereas a subclass of a sealed class can have multiple instances that can contain state. Let's look at an example in the mentioned steps:

  1. We will create a sealed class named ToastOperation. Under the same source file, we will define a ShowMessageToast subclass:
class ShowMessageToast(val message:String):ToastOperation()
  1. Also, we'll define a ShowErrorToast object:
object ShowErrorToast:ToastOperation()
  1. As you may have noted, I have...