https://kotlinlang.org logo
#getting-started
Title
# getting-started
j

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.
Copy code
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? 😅
s

Sam

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
private
.
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.
6
j

Jérémy CROS

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

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
2 Views