Kotlin教程:密封(Sealed)类声明与示例

2020-04-2311:33:55编程语言入门到精通Comments2,279 views字数 1511阅读模式

密封(Sealed)类是一个限制类层次结构的类。 可以在类名之前使用sealed关键字将类声明为密封类。 它用于表示受限制的类层次结构。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/18303.html

当对象具有来自有限集的类型之一,但不能具有任何其他类型时,使用密封类。
密封类的构造函数在默认情况下是私有的,它也不能允许声明为非私有。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/18303.html

密封类声明

sealed class MyClass

密封类的子类必须在密封类的同一文件中声明。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/18303.html

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()
}
Kotlin

密封类通过仅在编译时限制类型集来确保类型安全的重要性。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/18303.html

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() // 不起作用,因为密封类在另一个范围内定义。
}
Kotlin

密封类隐式是一个无法实例化的抽象类。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/18303.html

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

密封类和 when 的使用

密封类通常与表达时一起使用。 由于密封类的子类将自身类型作为一种情况。 因此,密封类中的when表达式涵盖所有情况,从而避免使用else子句。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/18303.html

示例:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/18303.html

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)
}  
`
Kotlin

执行上面示例代码,得到以下结果 -文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/18303.html

Circle area is 78.5
Square area is 25
Rectagle area is 20

//原文出自【易百教程】,商业转载请联系作者获得授权,非商业转载请保留原文链接:https://www.yiibai.com/kotlin/kotlin-sealed-class.html#article-start文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/18303.html

文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/18303.html
  • 本站内容整理自互联网,仅提供信息存储空间服务,以方便学习之用。如对文章、图片、字体等版权有疑问,请在下方留言,管理员看到后,将第一时间进行处理。
  • 转载请务必保留本文链接:https://www.cainiaoxueyuan.com/ymba/18303.html

Comment

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定