密封类是限制类层次结构的类。可以在类名之前使用“ sealed”关键字将一个类声明为密封类。它用于表示受限的类层次结构。
当对象具有有限集合中的一种类型但不能具有任何其他类型时,使用密封类。
默认情况下,密封类的构造函数是私有的,不能将其构造为非私有的。
sealed class MyClass
密封类的子类必须在与密封类本身相同的文件中声明。
sealed class Shape{ class Circle(var radius: Float): Shape() class Square(var length: Int): Shape() class Rectangle(var length: Int, var breadth: Int): Shape() object NotAShape : Shape() }
密封类通过仅在编译时限制类型集来确保类型安全的重要性。
sealed class A{ class B : A() { class E : A() //this works. } class C : A() init { println("sealed class A") } } class D : A() //this works { class F: A() //这不起作用,因为密封类是在另一个范围内定义的。 }
密封类是隐式的抽象类,无法实例化。
链接:https://www.learnfk.comhttps://www.learnfk.com/kotlin/kotlin-sealed-class.html
来源:LearnFk无涯教程网
sealed class MyClass fun main(args: Array<String>) { var myClass = MyClass() //编译器错误。密封类型不能被实例化。 }
密封类通常与when表达式一起使用。由于密封类的子类具有其自身的类型,因此是一种情况。因此,当密封类中的表达式涵盖所有情况时,请避免添加else子句。
例如:
sealed class Shape{ class Circle(var radius: Float): Shape() class Square(var length: Int): Shape() class Rectangle(var length: Int, var breadth: Int): Shape() // object NotAShape : Shape() } fun eval(e: Shape) = when (e) { is Shape.Circle ->println("Circle area is ${3.14*e.radius*e.radius}") is Shape.Square ->println("Square area is ${e.length*e.length}") is Shape.Rectangle ->println("Rectagle area is ${e.length*e.breadth}") //else -> "else case is not require as all case is covered above" // Shape.NotAShape ->Double.NaN } fun main(args: Array<String>) { var circle = Shape.Circle(5.0f) var square = Shape.Square(5) var rectangle = Shape.Rectangle(4,5) eval(circle) eval(square) eval(rectangle) }
输出:
Circle area is 78.5 Square area is 25 Rectagle area is 20
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)