Hi! I have one question regarding lazy variables. ...
# announcements
z
Hi! I have one question regarding lazy variables. Is something like that possible?
Copy code
val myNotRequiredStuff : SomeClass by lazy { SomeClass(...) }
...
fun onDestroy() {
    myNotRequiredStuff.useIfCreated {
        myNotRequiredStuff.destroy()
    }
}
o
To "destroy" the object within itself you can clear all instance variables. To "destroy" the object from outside, set the variable equal to null. Only the garbage collector will (eventually) destroy objects when they are no longer referenced.
j
I think you're looking for a way to check if the lazy initializer has ever been invoked, so that you can properly close resources if it has? I don't think there's any library support for it, I'd do something like this
Copy code
fun 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")
        }
    }
}
m
@zokipirlo You can try doing it like that:
Copy code
val 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:
Copy code
val myNotRequiredStuff = lazy { SomeClass(...) }

fun onDestroy() {
    if (myNotRequiredStuff.isInitialized()) {
        myNotRequiredStuff.value.destroy()
    }
}
z
@Ole K. Øverland (Norway) I didn't mean object deleting or deallocating. That's more android type of syntax, where you have onDestroy lifecycle to clean up everything
@Joris PZ I did exactly that with boolean 🙂
@maciejciemiega Yeah it's similar to boolean version... it's not pretty, to always write .value like in livedata 🙂
Thanks everyone for ideas 😉
m
I think the variant with boolean field is worse, because you have to remember to change it to
true
inside
lazy { … }
and compiler will not help you if you forget to do it. Version with separate delegate does it automatically.
2