网站地图xml文件济南房产信息网官网
网站地图xml文件,济南房产信息网官网,建设一个网站的流程.,帮别人做彩票网站使用sealed关键字声明一个密封类或者接口
sealed interface Errorsealed class IOError(): Error密封类和接口能够很好的控制继承#xff0c;在密封类和接口定义的模块和包外无法被继承
在编译期我们就已知了所有的密封类和接口的实现类。在某种意义上#xff0c;密封类类似…使用sealed关键字声明一个密封类或者接口
sealed interface Errorsealed class IOError(): Error密封类和接口能够很好的控制继承在密封类和接口定义的模块和包外无法被继承
在编译期我们就已知了所有的密封类和接口的实现类。在某种意义上密封类类似于枚举类枚举类型的值集也是受限制的但枚举常量只存在为单个实例而密封类的子类可以有多个实例每个实例都有自己的状态。
举例来说有个公共方法模块定义了一个顶级错误密封类Error只要是模块中捕获了Error的子类异常就证明是当前模块抛出的错误可以根据子类类型分别作出不同的处理。如果不是密封类其他模块也继承了Error类因为不是在当前模块定义的被当前模块捕获后没有相应的处理方式可能导致运行异常。因为密封类的特性所有子类型都是已知的不会被其他模块继承避免了上述未知异常 上述情况需要直接子类不能为open类型才能完美实现 package com.examplesealed interface Error
class CustomError() : Error package io.exampleimport com.example.Errorclass CustomError(): Error // 报错 -- Inheritor of sealed class or interface declared in package io.example but it must be in package com.example where base class is declared注意上边例子的包名在其他io包下继承密封类报错 密封类本身是抽象类不能直接实例化可以有抽象成员
密封类的构造函数可以是protected或者private默认为protected
sealed class IOError {constructor() { /*...*/ } // 默认protectedprivate constructor(description: String): this() { /*...*/ } // private// public constructor(code: Int): this() {} // 报错 -- Error: public and internal are not allowed
}直接子类位置Location of direct subclasses
直接子类必须在相同的包内声明。子类可以是顶层类也可以嵌套在任意数量的其他命名类、命名接口或命名对象内。子类可以具有任何可见性只要它们符合kotlin的正常继承规则。密封类的子类必须具有正确的限定名称。子类不能是局部的也不能是匿名对象 枚举不能继承密封类但是能实现密封接口 这些限制不适用于间接子类。如果密封类的直接子类没有标记为密封类那么它可以根据其修饰符允许的任何方式进行扩展
sealed interface Error // has implementations only in same package and modulesealed class IOError(): Error // extended only in same package and module
open class CustomError(): Error // can be extended wherever its visible多平台继承
在以后章节中讲解
密封类和When表达式
使用密封类的主要好处是在when表达式中使用它们时发挥作用。如果可以验证语句涵盖所有情况则不需要在语句中添加else子句
fun log(e: Error) when(e) {is FileReadError - { println(Error while reading file ${e.file}) }is DatabaseError - { println(Error while reading from database ${e.source}) }is RuntimeError - { println(Runtime error) }// the else clause is not required because all the cases are covered
}when expressions on expect sealed classes in the common code of multiplatform projects still require an else branch. This happens because subclasses of actual platform implementations aren’t known in the common code.
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/diannao/91844.shtml
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!