Kotlin specifies that all non-abstract attribute members in a class must be initialized when the object is created, so if the attribute cannot be initialized by a parameter, it needs to be done via lazy initialization.

By lazy {} — for val

Features:

  • A reference is immutable, that is, it must be val, not var
  • Assignment is performed only when it is called for the first time. Once assigned, it cannot be changed later
  • The default is thread-safe
class Bird(val weight: Double.val age: Int.val color: String) {
   val sex: String by lazy {
 if (color == "yellow") "male" else "female"
   }
 val sex1: String by lazy(LazyThreadSafetyMode.PUBLICATION) {
 // Parallel mode
      if (color == "yellow") "male" else "female"
   }
 val sex2: String by lazy(LazyThreadSafetyMode.NONE) {
 // There is no thread guarantee and no thread overhead
      if (color == "yellow") "male" else "female"}}Copy the code

lateinit

Features:

  • Used primarily for variables declared by var
  • Cannot be used for basic data types, such as Int, Long, and needs to be wrapped in a wrapper class
class Bird(val weight: Double.val age: Int.val color: String) {
   lateinit var sex: String // Sex can delay initialization

   fun printSex(a) {
      this.sex = if (this.color == "yellow") "male" else "female"
      println(this.sex)
   }
}
Copy the code

Lateinit and? = Time when null is used

  • Lateinit: Very sure you will instantiate objects for variables you use
  • ? =null: Depends on the object provided by others, not sure whether others will instantiate to return the real object