Kotlin Sealed类

密封(Sealed)类是一个限制类层次结构的类。 可以在类名之前使用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() // 不起作用,因为密封类在另一个范围内定义。
}

密封类隐式是一个无法实例化的抽象类。

sealed class MyClass
fun main(args: Array<String>)
{
    var myClass = MyClass() // 编译器错误,密封类型无法实例化。
}

密封类和 when 的使用

密封类通常与表达时一起使用。 由于密封类的子类将自身类型作为一种情况。 因此,密封类中的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

上一篇:Kotlin Data类

下一篇:Kotlin扩展函数

关注微信小程序
程序员编程王-随时随地学编程

扫描二维码
程序员编程王

扫一扫关注最新编程教程