Jérémy CROS

08/22/2022, 2:34 PM
Hi guys 🙂 We wrote something like that today during a pair programing session and it occurred to us that we had no idea what the lifecycle of the variable was.
private var aVariableToKeepTrackOfSomeData : SomeClass? = null

fun AnotherClass.myExtentionFunction() {
    // do stuff here with the variable
Is it scoped to the application? Does that look like a bad idea? 😅


08/22/2022, 2:36 PM
The lifecycle is the same as the application, yes. The scope is the file in which it’s declared, since it’s marked
Whether it’s a bad idea really depends on how you’re using it 😄
But it’s quite likely to be a bad idea if you’re mutating it as a side effect of an extension function. It could make testing very difficult, it could introduce problems when multithreading, and it could confuse people who are calling the function.

Jérémy CROS

08/22/2022, 2:41 PM
Ok, that’s what we figured, thanks for confirmation and explanations 🙏

Robert Williams

08/22/2022, 2:49 PM
If you really care about implementation details the lifecycle is controlled by the ClassLoader that loads the Class generated from the file (normally something like FooKt.class)
It's possible in Java to have multiple ClassLoaders with different lifecycles but it normally causes more problems than it solves