zokipirlo
12/17/2020, 8:21 AMval myNotRequiredStuff : SomeClass by lazy { SomeClass(...) }
...
fun onDestroy() {
myNotRequiredStuff.useIfCreated {
myNotRequiredStuff.destroy()
}
}
Ole K. Øverland (Norway)
12/17/2020, 8:31 AMJoris PZ
12/17/2020, 8:37 AMfun main() {
val foo = Foo()
foo.destroy()
println(foo.bar)
foo.destroy()
}
class Foo {
private var barCreated = false;
val bar by lazy {
barCreated = true;
"Hello, world"
}
fun destroy() {
if (barCreated) {
println("Destroying bar")
} else {
println("Not destroying bar")
}
}
}
maciejciemiega
12/17/2020, 4:05 PMval myNotRequiredStuffDelegate = lazy { SomeClass(...) }
val myNotRequiredStuff: SomeClass by myNotRequiredStuffDelegate
fun onDestroy() {
if (myNotRequiredStuffDelegate.isInitialized()) {
myNotRequiredStuff.destroy()
}
}
Or without declaring 2 fields, having just a delegate and access the value using .value
on it:
val myNotRequiredStuff = lazy { SomeClass(...) }
fun onDestroy() {
if (myNotRequiredStuff.isInitialized()) {
myNotRequiredStuff.value.destroy()
}
}
zokipirlo
12/17/2020, 8:40 PMzokipirlo
12/17/2020, 8:41 PMzokipirlo
12/17/2020, 8:43 PMzokipirlo
12/17/2020, 8:43 PMmaciejciemiega
12/17/2020, 9:20 PMtrue
inside lazy { … }
and compiler will not help you if you forget to do it. Version with separate delegate does it automatically.