Skip to content

Instantly share code, notes, and snippets.

@ajaypro
Last active August 30, 2019 10:11
Show Gist options
  • Save ajaypro/2d4c05bb293dc4599075e9b3b96188fd to your computer and use it in GitHub Desktop.
Save ajaypro/2d4c05bb293dc4599075e9b3b96188fd to your computer and use it in GitHub Desktop.
Kotlin lazy functions
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