// 定义密封类
sealed class Shape {
// 圆形子类
data class Circle(val radius: Double) : Shape() {
fun calculateArea() = Math.PI * radius * radius
}
// 矩形子类
data class Rectangle(val width: Double, val height: Double) : Shape() {
fun calculateArea() = width * height
}
// 三角形子类
data class Triangle(val base: Double, val height: Double) : Shape() {
fun calculateArea() = 0.5 * base * height
}
}
fun main() {
val shapes: List<Shape> = listOf(
Shape.Circle(5.0),
Shape.Rectangle(4.0, 3.0),
Shape.Triangle(6.0, 4.0)
)
shapes.forEach { shape ->
val area = when (shape) {
is Shape.Circle -> shape.calculateArea()
is Shape.Rectangle -> shape.calculateArea()
is Shape.Triangle -> shape.calculateArea()
}
println("The area of the ${shape::class.simpleName} is $area")
}
}
- 密封类定义:
- 使用
sealed class
关键字定义了Shape
密封类。
- 它有三个子类
Circle
、Rectangle
和Triangle
,这些子类必须在密封类内部或与密封类在同一文件中定义。
when
表达式处理:
- 在
main
函数中,创建了一个包含不同形状对象的列表。
- 使用
forEach
遍历列表,在when
表达式中,通过is
关键字判断对象的具体类型,然后调用相应的calculateArea
方法计算面积。这样可以对密封类的不同子类型进行特定操作。