Kotlin - Property initialization using “by lazy” vs. “lateinit”

后端 未结 8 1065
没有蜡笔的小新
没有蜡笔的小新 2020-11-29 14:50

In Kotlin if you don\'t want to initialize a class property inside the constructor or in the top of the class body, you have basically these two options (from the language r

相关标签:
8条回答
  • 2020-11-29 15:41

    If you are using Spring container and you want to initialize non-nullable bean field, lateinit is better suited.

        @Autowired
        lateinit var myBean: MyBean
    
    0 讨论(0)
  • 2020-11-29 15:42

    lateinit vs lazy

    1. lateinit

      i) Use it with mutable variable[var]

      lateinit var name: String       //Allowed
      lateinit val name: String       //Not Allowed
      

      ii) Allowed with only non-nullable data types

      lateinit var name: String       //Allowed
      lateinit var name: String?      //Not Allowed
      

      iii) It is a promise to compiler that the value will be initialized in future.

    NOTE: If you try to access lateinit variable without initializing it then it throws UnInitializedPropertyAccessException.

    1. lazy

      i) Lazy initialization was designed to prevent unnecessary initialization of objects.

      ii) Your variable will not be initialized unless you use it.

      iii) It is initialized only once. Next time when you use it, you get the value from cache memory.

      iv) It is thread safe(It is initializes in the thread where it is used for the first time. Other threads use the same value stored in the cache).

      v) The variable can only be val.

      vi) The variable can only be non-nullable.

    0 讨论(0)
提交回复
热议问题