当前位置:网站首页>Kotlin:Sealed class密封类详解
Kotlin:Sealed class密封类详解
2022-07-28 17:06:00 【明飞1987】
一:密封类的定义
在类名之前使用sealed关键字将类声明为密封类。 密封类仅在编译时限制类型集来确保类型安全的重要性。 密封类隐式是一个无法实例化的抽象类。
二:密封类所具有的特性和与别的类具有不同之处
①Sealed class(密封类) 是一个有特定数量子类的类,看上去和枚举有点类似,所不同的是,在枚举中,我们每个类型只有一个对象(实例);而在密封类中,同一个类可以拥有几个对象。
②Sealed class(密封类)的所有子类都必须与密封类在同一文件中
③Sealed class(密封类)的子类的子类可以定义在任何地方,并不需要和密封类定义在同一个文件中
④Sealed class(密封类)没有构造函数,不可以直接实例化,只能实例化内部的子类
二:如何获取密封类里面的函数方法
只能创建密封类子类对象 通过密封类的子类对象调用密封类里的函数方法
sealed class SealedClass{
class SealedClass1():SealedClass()
class SealedClass2():SealedClass()
fun hello(){
println("Hello World ... ")
}
}
只能通过密封类内部的子类实例化对象,这时就可以执行里面的方法了
fun main(args:Array<String>){
var sc:SealedClass = SealedClass.SealedClass1()
sc.hello()
}
三:
密封类通常与表达when时一起使用。 由于密封类的子类将自身类型作为一种情况。 因此,密封类中的when表达式涵盖所有情况,从而避免使用else子句。
sealed class MyColor {
class Yellow : MyColor()
class Red : MyColor()
class Black : MyColor()
}
fun evals(color: MyColor) =
when (color) {
is MyColor.Yellow -> println("yellow")
is MyColor.Red -> println("red")
is MyColor.Black -> println("black")
}//todo 不需要使用else了
fun main(args: Array<String>) {
evals(MyColor.Black())
}
边栏推荐
- 2022.7.26 constructor, interview: the role of new, deep copy and shallow copy
- 实验楼----PHP大法
- @Autowired与@Resource区别
- What skills do you need to master when learning software testing zero foundation?
- UE5 GAS 学习笔记 1.4属性集
- SQL Server stuff and for XML path
- LeetCode_ 343_ integer partition
- UE5 GAS 学习笔记8.0参考资料
- MYSQL入门与进阶(一)
- Software testing needs more and more talents, but fewer people are on the road of testing?
猜你喜欢

高德地图实现自定义小蓝点 自定义点标记 绘制多边形/圆形区域 根据地图的移动显示或者隐藏自定义点标记的相关实现

记录自己在厦门两年来的面试经历--完结篇

It is said that software testing is the worst in the IT industry. Is that so?

Gateway入门

GIS数据漫谈(六)— 投影坐标系统

什么样的知识付费系统功能,更有利于平台与讲师发展?

实验楼----PHP大法

1.3 linked list

Record your interview experience in Xiamen for two years -- Conclusion

Composition and principle of vector network analyzer (vector network)
随机推荐
What is the future of software testing?
MYSQL入门与进阶(十)
Introduction to CC cable of USB type-C
npm 无法将“npm”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。请检查名称的拼写,如果包括路径,请确保路径正确,然后再试一次。
UE5 GAS 学习笔记 1.9 技能系统全局类(AbilitySystemGlobals)
haproxy实现代理配置
注意力机制及代码实现
UE5 GAS 学习笔记 1.8 游戏特效(GameplayCue)
Ue5 gas learning notes 0.1 case Preview
MYSQL入门与进阶(一)
leetcode 二叉树类
MYSQL入门与进阶(九)
LeetCode_ 96_ Different binary search trees
腾讯汤道生:开源是产业互联网时代新的生产方式和协作模式
Introduction to advanced design system (ads) 2009 RF simulation
Error 2003 (HY000) can't connect to MySQL server on 'localhost3306' (10061) solution
LeetCode_63_不同路径Ⅱ
Go语言系列之日志库zap
Apple develops a complete creation process of Apple certificate and description file
Examples of AC simulation and S-parameter simulation of ADS simulation