# Kotlin: lateinit vs lazy ###### tags: `Kotlin` [TOC] # Introduction What are both lateinit & lazy for? Sometimes, we just want to initialize the variables later, instead of immediately after jumping into the page. Another reason for using them, is to avoid the use of optionals (?), every time we use the variables. Therefore, we have 2 different types of late initialization: **lateinit && lazy** # Lateinit For **lateinit**, it can only be used with **var**. If **val** is used, it will tell you that lateinit cannot be used with mutable properties. ```kotlin= private lateinit var dealBind : ActivityProductBinding ``` ## Check Initialization If lateinit is used, but the initialization was not done, then we will either get an error thrown or a crash. Therefore, it is essential to check the instantiation. ```kotlin= if(::dealVMShared.isInitialized){ dealVMShared.setPriceFilter() } ``` # Lazy Unlike **lateinit**, it has to be used with **val** and the value gets computed only upon first access. >**NOTE:** [color=red] > Another thing to take into account, **lazy** has 2 types: **by lazy** and **assign lazy**. ```kotlin= val usingBy by lazy {"test"} -> gives String val usingAssign = lazy { "test" } -> gives Lazy<String> //With this one, you can check whether it is initialized or check its value. ```