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 密封类提供了一种更灵活、类型安全的方式来表示具有有限可能子类的类型。它们有助于减少错误,提高代码的可读性和可维护性。