Android class with context in object field in Kotlin
Is it good to have a property in an objectclass in Kotlin that has a context in it? In Android, it is bad practice to place context-related objects in static fields. Android studio even highlights it and gives a warning, unlike Kotlin where there is no warning. Object example:
object Example {
lateinit var context: Context
fun doStuff(){
//..work with context
}
}
source to share
Since they object
are single, they have one static instance. So if you give them a property context
, you still save in a context
static way.
This will have the same consequences as putting context
in a static field in Java.
If you write equivalent code that Kotlin generates for object
in Java, this will actually result in correct lint errors:
public class Example {
// Do not place Android context classes in static fields; this is a memory leak
// (and also breaks Instant Run)
public static Context context;
// Do not place Android context classes in static fields (static reference to
// Example which has field context pointing to Context); this is a memory leak
// (and also breaks Instant Run)
public static Example INSTANCE;
private Example() { INSTANCE = this; }
static { new Example(); }
}
source to share