Kotlin 密封類(sealed class)是一種限制其子類的類。它們的主要應用場景包括:
sealed class GameCharacter {
data class Standing(val position: Vector2D) : GameCharacter()
data class Moving(val direction: Vector2D, val speed: Float) : GameCharacter()
data class Jumping(val position: Vector2D, val height: Float) : GameCharacter()
}
Boolean
或 Unit
類型。sealed class Result<out T> {
data class Success<out T>(val data: T) : Result<T>()
data class Failure(val error: String) : Result<Nothing>()
}
Any
類型,從而提高代碼的類型安全性和可讀性。sealed class Shape {
data class Circle(val radius: Double) : Shape()
data class Rectangle(val width: Double, val height: Double) : Shape()
data class Triangle(val base: Double, val height: Double) : Shape()
}
when
表達式,可以根據密封類子類的類型執行相應的代碼塊。fun processShape(shape: Shape) {
when (shape) {
is Shape.Circle -> println("Processing circle with radius ${shape.radius}")
is Shape.Rectangle -> println("Processing rectangle with width ${shape.width} and height ${shape.height}")
is Shape.Triangle -> println("Processing triangle with base ${shape.base} and height ${shape.height}")
}
}
總之,Kotlin 密封類提供了一種更靈活、類型安全的方式來表示具有有限可能子類的類型。它們有助于減少錯誤,提高代碼的可讀性和可維護性。