The Lateinit
and Lazy
initializations are two initialization properties in the Kotlin language. It is necessary to know when to use Lateinit
and when to use theLazy
initialization.
Lateinit
Use Lateinit
:
var
keyword.Lateinit
variables can be declared inside the class.
Lateinit
does not allocate memory before initializing.
Lateinit
Lateinit
, the variable can’t be of the null type.Lateinit
cannot be used for primitive datatypes, i.e., Long and int.Lateinit
variables without initializing, it will throw an exception stating that it is not initialized or properly being accessed.private lateinit var educativeshot : educativeshot
It can later on be initialized in the educativeshot
class
educativeshot = educative()
Lazy
initializationLazy
initialization, your variable will not be initialized unless you call/use it.Lazy
initialization initializes the variable once; that same value is then used throughout the code.val
property.
-It is preferred when the variable is to be shared by all and only initialized once.Lazy
initializationLazy
object returns the previously initialized value when accessed later.Lazy
Initialization causes memory leakage when used on a retained fragment as it holds a reference to the old view.val educative: String by lazy {val educativeshot = "this value"}
class educative{private val edobject: educativeshot by lazy {educativeshot()}}
Lateinit
vs. Lazy
initializationLateinit
is used.Lateinit
initialization is dependent on the user.Lazy
initialization is thread-safe.Lateinit
can only be used with var
.Lazy
initialization is used with the val
property.