skizoqa.blogg.se

Sealed class serializable kotlin
Sealed class serializable kotlin










sealed class serializable kotlin

It means we can't instantiate sealed classes. If we try to create a sub class of a sealed class in other Kotlin file, we will get an error.

sealed class serializable kotlin

It is important to note that all the sub classes of a sealed class must be declared in the same Kotlin file. Sealed classes are created using the sealed keyword. Ĭhild classes of a sealed class can be of different types like: data, object or normal class.But in Sealed class, different child classes can have different set of properties and functions. In Enum, each instance has same set of properties and functions. It means each object of child class(of sealed class) can have a state. The key differences between Sealed classes and Enums are:Įach enum instance exists only as a single instance, whereas a child class of a sealed class can have multiple instances. In Enum, we can have particular types defined in it. The similar functionality is also provided by Enum. Difference between Sealed class and Enum class This is useful when we know all the subtypes of a parent class and don't want to create a child class aprt from what we know. A class can have some specified child classes only. This is what we can achieve through Sealed classes. We also want to make sure that apart from this usecase, no other class should inherit this Question class. Now we want to create a class Question and all the question type should inherit this class. The question type can be Easy, Moderate or Difficult. Suppose there is a need to declare classes based on types of questions in an examination. Let us understand it with the help of an example. It means the object of sealed class can have only one of the defined types. Sealed classes are new in Kotlin and were not present in Java.Ī sealed class is used to represent restricted class hierarchies. In this tutorial we will learn about Kotlin Sealed class.












Sealed class serializable kotlin