Kotlin - 密封类

Kotlin - 密封类 首页 / Kotlin入门教程 / Kotlin - 密封类

密封类是限制类层次结构的类。可以在类名之前使用“ 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

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

零基础学Java -〔臧萌〕

正则表达式入门课 -〔涂伟忠〕

分布式数据库30讲 -〔王磊〕

Go 并发编程实战课 -〔晁岳攀(鸟窝)〕

操作系统实战45讲 -〔彭东〕

遗留系统现代化实战 -〔姚琪琳〕

Python实战 · 从0到1搭建直播视频平台 -〔Barry〕

AI大模型系统实战 -〔Tyler〕

互联网人的数字化企业生存指南 -〔沈欣〕

好记忆不如烂笔头。留下您的足迹吧 :)