Kotlin 简明教程
Kotlin - Sealed Class
在本章中,我们将学习另一种称为“密封”类的类类型。这种类型的类用于表示受限的类层次结构。密封允许开发人员维护预定义类型的类型。为了创建一个密封类,我们需要使用关键字“sealed”作为该类的修饰符。一个密封类可以有自己的子类,但所有这些子类都需要与密封类一起声明在同一个 Kotlin 文件中。在以下示例中,我们将看到如何使用密封类。
In this chapter, we will learn about another class type called “Sealed” class. This type of class is used to represent a restricted class hierarchy. Sealed allows the developers to maintain a data type of a predefined type. To make a sealed class, we need to use the keyword “sealed” as a modifier of that class. A sealed class can have its own subclass but all those subclasses need to be declared inside the same Kotlin file along with the sealed class. In the following example, we will see how to use a sealed class.
sealed class MyExample {
class OP1 : MyExample() // MyExmaple class can be of two types only
class OP2 : MyExample()
}
fun main(args: Array<String>) {
val obj: MyExample = MyExample.OP2()
val output = when (obj) { // defining the object of the class depending on the inuputs
is MyExample.OP1 -> "Option One has been chosen"
is MyExample.OP2 -> "option Two has been chosen"
}
println(output)
}
在上面的示例中,我们有一个名为“MyExample”的密封类,它只能是两种类型之一——一种是“OP1”,另一种是“OP2”。在主类中,我们在类中创建一个对象,并在运行时分配它的类型。现在,由于这个“MyExample”类是密封的,我们可以将“when ” 子句应用于运行时以实现最终输出。
In the above example, we have one sealed class named “MyExample”, which can be of two types only - one is “OP1” and another one is “OP2”. In the main class, we are creating an object in our class and assigning its type at runtime. Now, as this “MyExample” class is sealed, we can apply the “when ” clause at runtime to implement the final output.
在密封类中,我们不需要使用任何不必要的“else”语句来使代码复杂化。以上代码段将在浏览器中产生以下输出。
In sealed class, we need not use any unnecessary “else” statement to complex out the code. The above piece of code will yield the following output in the browser.
option Two has been chosen