企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
## 印章类(密封类) [TOC] ### 基本定义 通过enum关键字可以定义一个枚举类,枚举类让一个类拥有了有限多个常量。通过sealed关键字,则可以定义一个印章类(Sealed class又有人翻译成密封类),印章类让一个类拥有了有限多个子类。印章类甚至可以理解为一个特殊的枚举类。印章类本身不能被实例化。 现实生活中我们知道,四则运算包括加减乘除,如果把“加减乘除”定义为常量,我们可以用枚举实现。那如果,想把“加减乘除”定义成类,则可以用印章类。 印章类的最简单结构如下: ![](http://upload-images.jianshu.io/upload_images/7368752-4a9b06c149d991aa.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 我们把“四则运算包括加减乘除”这样的情况,定义为一个印章类,参考代码: ![](http://upload-images.jianshu.io/upload_images/7368752-d5a70aafa606eaed.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 通过例子,我们看到了怎么去定义印章类。看到了印章类包含的类可以被实例化。印章类本身不能被实例化。 ### 分支操作 但是上面的例子,并没有任何的实际意义。想用**Add、Substract、Multiply、Divide**做最基本的分支操作,我们还需要做如下的更改,参考代码: ~~~ sealed class Operation { class Add : Operation()//加//这里是继承 class Substract : Operation()//减 class Multiply : Operation()//乘 class Divide : Operation()//除 } fun printInfo(op: Operation) { if (op is Operation.Add) { println("加 操作") } else if (op is Operation.Substract) { println("减 操作") } else if (op is Operation.Multiply) { println("乘 操作") } else if (op is Operation.Divide) { println("除 操作") } } fun main(args: Array<String>) { printInfo(Operation.Add()) } ~~~ 运行结果 ``` 加 操作 Process finished with exit code 0 ``` 针对以上代码的第11行到14行,表示Add、Substract、Multiply、Divide继承至Operation,如果你有继承的概念,代码可以看到。如果,没有继承的概念,看完后面的继承相关的知识点,在回过来看这里。 ### 携带自定义属性 进一步加大难度,印章类包含的有限的类还可以随意包含属性,我们把上面的逻辑进一步完善,参考代码: ~~~ sealed class MyOperation() { //自定义属性 class Add(val num1: Int, val num2: Int) : MyOperation()//加//这里是继承 class Substract(val num1: Int, val num2: Int) : MyOperation()//减 class Multiply(val num1: Int, val num2: Int) : MyOperation()//乘 class Divide(val num1: Int, val num2: Int) : MyOperation()//除 } fun operation(op: MyOperation) { if (op is MyOperation.Add) { println("${op.num1}+${op.num2}=${op.num1 + op.num2}")//取出自定义的属性 } else if (op is MyOperation.Substract) { println("${op.num1}-${op.num2}=${op.num1 - op.num2}") } else if (op is MyOperation.Multiply) { println("${op.num1}*${op.num2}=${op.num1 * op.num2}") } else if (op is MyOperation.Divide) { println("${op.num1}/${op.num2}=${op.num1 / op.num2}") } } fun main(args: Array<String>) { operation(MyOperation.Add(5,2)) operation(MyOperation.Substract(5,2)) operation(MyOperation.Multiply(5,2)) operation(MyOperation.Divide(5,2)) } ~~~ 运行结果 ``` 5+2=7 5-2=3 5*2=10 5/2=2 Process finished with exit code 0 ``` 枚举和印章类都是可以完成分支操作的,枚举的常量也可以携带自定义的属性,印章类包含的类也可以携带自定义属性。但是,枚举常量携带的自定义属性,是固定不变量的。印章类包含的类携带的属性,则是可以交给外接灵活赋值的。 作为了解,其实枚举类和印章类和when表达式配合起来,看着结构更清晰。when表达式我们后面再说,这里可以简单感受下。鼠标放在if关键字这里将得到如下提示,参考截图: ![](http://upload-images.jianshu.io/upload_images/7368752-71ee764c9dbaa9ec.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)