"Kotlin Basics 3" keywords: lateinit and by lazy

lateinit: lazy initialization

java:

private LoginPresenter loginPresenter;

kotlin:

private lateinit var loginPresenter: LoginPresenter

by lazy: lazy initialization
Lazy initialization is a common pattern where parts of the object are not created on demand until the property is first accessed, when the initialization process consumes a lot of resources and the data is not always needed when using the object , this is very useful

val nameB: String by lazy {
    
    
    println("getLazy")
    "123"
}
println(nameB)
println(nameB)

Enter the result:

System.out: getLazy
System.out: 123
System.out: 123

The first thing to note is:

  • by lazy can only act on properties marked with the val keyword
  • The contents of "lazy{}" will be initialized when the property is used
  • And when the property is called again, only the result will be obtained, and the running process of lazy{} will not be executed again

Guess you like

Origin blog.csdn.net/qq_35091074/article/details/123308074