lateinit 关键字
The lateinit keyword in Kotlin is used to declare(声明) a property that will be initialized later. It allows you to avoid(避免) null checks or the use of the null type for properties that you are certain will be initialized before use, but for some reason, you can't initialize them immediately(立即) at declaration.
Here are some important points about lateinit:
- Only for
varProperties: Thelateinitmodifier(修饰语) can only be applied tovarproperties, notvalproperties. - Non-Nullable Types: The property must have a non-nullable type.
- Initialization Check: You can check whether a
lateinitproperty has been initialized using the::propertyName.isInitializedsyntax. - Used Only for Class Properties:
lateinitcannot be used for local variables.
Let's look at an example to illustrate(说明,阐明) the usage of lateinit.
Without lateinit
You might need to initialize a property with null and perform null checks later, which is cumbersome(难操作的,麻烦的).
class MyClass {
private var myProperty: String? = null
fun initializeProperty() {
myProperty = "Hello, World!"
}
fun printProperty() {
if (myProperty != null) {
println(myProperty)
} else {
println("Property not initialized")
}
}
}With lateinit
Using lateinit, you can avoid nullable types and null checks.
class MyClass {
private lateinit var myProperty: String
fun initializeProperty() {
myProperty = "Hello, World!"
}
fun printProperty() {
if (this::myProperty.isInitialized) {
println(myProperty)
} else {
println("Property not initialized")
}
}
}内容来自 GPT-4o
PS. 其实看到late-init就知道什么作用了
评论已关闭