📅  最后修改于: 2021-01-05 08:04:04             🧑  作者: Mango
密封类是限制类层次结构的类。可以在类名之前使用“ 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() //This won't work,because sealed class is defined in another scope.
}
密封类隐式是不能实例化的抽象类。
sealed class MyClass
fun main(args: Array)
{
var myClass = MyClass() //compiler error. sealed types cannot be instantiated.
}
密封类通常与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) {
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