I'm using Kotlin for Android development. Interesting question. In Java saving Context in static field is a memory leak. But if I'm storing context in Kotlin companion object, Android Studio doesn't say that it's a memory leak. It's means that in Java bytecode conpanion object is not a static code? For example:
class MyApp : Application() {
override fun onCreate() {
super.onCreate()
appContext = applicationContext
}
companion object {
lateinit var appContext: Context
}
}
Here is no memory leak? Thanks for answers :)
Your code does in fact store a Context
in a static way, it's just that lint can't pick it up and warn you for some reason.
In this specific case, however, you're not really at risk of creating a memory leak. You're storing your Application
object itself statically, which will be alive for the entirety of your application's life - just like static variables. You'd be in trouble if this was some other, shorter lived Context
, but the application Context
should be fine.
For reference about whether it's safe to do this: