Kotlin - 密封類



本章我們將學習另一種稱為“密封”類的類型別。這種型別的類用於表示受限的類層次結構。密封類允許開發者維護預定義型別的資料型別。要建立密封類,我們需要使用關鍵字“sealed”作為該類的修飾符。密封類可以有自己的子類,但所有這些子類都需要與密封類一起在同一個 Kotlin 檔案中宣告。在下面的示例中,我們將看到如何使用密封類。

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”子句來實現最終輸出。

在密封類中,我們不需要使用任何不必要的“else”語句來使程式碼複雜化。上面的程式碼將在瀏覽器中產生以下輸出。

option Two has been chosen
廣告