当前位置:网站首页>Delay initialization and sealing classes
Delay initialization and sealing classes
2022-07-06 08:35:00 【So, dream】
Delay initialization
background
Kotlin The variable non nullability feature is provided to suppress the null pointer problem .
This feature ensures program security while , It also brings us some coding problems .
Case study : Just imagine , There is a global variable in your program a , Variable a It was not initialized at the beginning of creation , So you make it equal to null.
hypothesis a The type of String, Because to guarantee a Non empty , So its type is declared as String?
private var a: String? = null
Next , Every time you need to call a The method in , All of them should be judged as empty ( Even if it has already been initialized ), Otherwise, you cannot compile !
When there are more and more instances of global variables in the code , This problem will become more obvious .
Delay initialization
To solve this problem ,Kotlin Use lateinit Keyword initializes variables .
private lateinit var a: String
lateinit Keyword telling Kotlin compiler , I will be in Then initialize the variable , So you don't have to assign a variable to null.
such , When calling global variables a Method in , There is no need to judge the empty space .
When using this object , It needs to be initialized , Otherwise, there will be a runtime error !
Avoid repeated initialization
To avoid repeated initialization of variables , You can use the following code
if (!::a.isInitialized) {
// Judge a Whether to initialize , If the execution code block is not initialized
a = "ming ming" // Yes a Perform initialization operation
}
::object.isInitialized It is a fixed writing method for judging initialization .
Sealing class
background
Create a new one Result.kt file , Write the following code in the file :
interface Result
class Success(val message:String):Result
class Failure(val error: Exception):Result
A is defined in the code Result Interface , Used to represent the execution result of an operation .
Define two classes to implement Result Interface ,Success Class is used to represent the result of success ,Failture Class is used to represent the result of failure .
Let me define one more getResultMessage(), Information used to execute the final execution result , The code is as follows
fun getResultMessage(result: Result) = when(result){
is Success -> result.message
is Failure -> result.error.message
else -> throw IllegalArgumentException()
}
getResultMessage() Method to receive a Result Parameters .
We use it when Sentence to judge Result The type of , If Success, Print success message , If Failture Return error message .
Be reasonable , This should end the code . Because the execution result of the code is either successful , Or failure , There is nothing else .
But for Satisfy Kotlin The grammar check of , At the end, I wrote a else To throw an exception ( Actually this else Can never reach ).
Besides , If we add another class inheritance Result Interface , And forgot to getResultMessage() Add the corresponding execution code ,
When the code is executed, it will be thrown directly else The abnormal .
Sealing class
Sealed classes can easily solve the above problems , To declare a sealed class, you only need to add keywords in front of the class sealed.
take Result The interface is transformed into a sealed class
sealed class Result
class Success(val message:String):Result()
class Failure(val error: Exception):Result()
The next in when Pass in the sealed class as a condition ,Kotlin It will check the subclasses of the seal class , And force you to deal with the conditions corresponding to each subclass , This ensures that even if you don't write else Conditions , There will be no missing branches .
fun getResultMessage(result: Result) = when(result){
is Success -> result.message
is Failure -> result.error.message
}
When we build a new one Others Class inheritance Result Sealing class ,getResultMessage() Will report a mistake .
We can go through Add remaining branches To add the processing of the corresponding conditions of all subclasses .
边栏推荐
- 2022 Inner Mongolia latest construction tower crane (construction special operation) simulation examination question bank and answers
- Mobile phones and computers on the same LAN access each other, IIS settings
- 3. File operation 3-with
- C語言雙指針——經典題型
- 堆排序详解
- 被破解毁掉的国产游戏之光
- [cloud native topic -45]:kubesphere cloud Governance - Introduction and overall architecture of enterprise container platform based on kubernetes
- Deep analysis of C language pointer
- [luatos-air551g] 6.2 repair: restart caused by line drawing
- gcc动态库fPIC和fpic编译选项差异介绍
猜你喜欢
JVM performance tuning and practical basic theory - Part 1
深度剖析C语言指针
Let the bullets fly for a while
生成器参数传入参数
堆排序详解
根据csv文件某一列字符串中某个数字排序
延迟初始化和密封类
MySQL learning record 10getting started with JDBC
Zhong Xuegao, who cannot be melted, cannot escape the life cycle of online celebrity products
Mobile phones and computers on the same LAN access each other, IIS settings
随机推荐
LDAP应用篇(4)Jenkins接入
电脑F1-F12用途
【Nvidia开发板】常见问题集 (不定时更新)
The ECU of 21 Audi q5l 45tfsi brushes is upgraded to master special adjustment, and the horsepower is safely and stably increased to 305 horsepower
CISP-PTE实操练习讲解
egg. JS project deployment online server
Pointer advanced --- pointer array, array pointer
Problems in loading and saving pytorch trained models
Purpose of computer F1-F12
Mobile phones and computers on the same LAN access each other, IIS settings
swagger设置字段required必填
被破解毁掉的国产游戏之光
Introduction to the differences between compiler options of GCC dynamic library FPIC and FPIC
hutool优雅解析URL链接并获取参数
Browser thread
PC easy to use essential software (used)
2022 Inner Mongolia latest construction tower crane (construction special operation) simulation examination question bank and answers
Vocabulary notes for postgraduate entrance examination (3)
torch建立的网络模型使用torchviz显示
Visual implementation and inspection of visdom