Last active
August 30, 2019 10:11
-
-
Save ajaypro/2d4c05bb293dc4599075e9b3b96188fd to your computer and use it in GitHub Desktop.
Kotlin lazy functions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
When we have to define a variable that will be later initialized as done below. | |
fun main() { | |
var lazyValue: Int? = null | |
fun getlazyValue(): Int?{ | |
if(lazyValue == null){ | |
lazyValue = 45 | |
} | |
return lazyValue!! | |
} | |
} | |
**Better way** | |
fun main() { | |
val lazyValue by lazy {45} | |
} | |
* The variable won't get initiliazed untill someone uses it for fist time. | |
* Here kotlin use property delegates that delegates the logic to somewhere else which run a logic to return | |
the variable. | |
[Property Delegate Ref](https://medium.com/rocket-fuel/kotlin-by-property-delegation-create-reusable-code-f2bc2253e227) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment