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
    }
}

      

+3


source to share


2 answers


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(); }

}

      

+7


source


The reason you don't get warnings is because Android studio does not have mature fleece validation rules for Kotlin used for Android. As soon as toolkit team

update them lint check rules

for kotlin with android, the warning will appear again.



+1


source







All Articles