Android class with context in object field in Kotl

2019-06-19 23:44发布

问题:

Is it ok to have a property in object class in Kotlin that has a context in it? In Android it is a bad practice to put context related objects in static fields. Android studio even highlights it and gives a warning unlike Kotlin where there is no warning. Example object:

object Example {
    lateinit var context: Context

    fun doStuff(){
        //..work with context
    }
}

回答1:

Since objects are singletons, they have a single static instance. So if you give them a context property, you're still storing a Context in a static way.

This will have the exact same consequences as putting a Context in a static field in Java.


If you write the equivalent code that Kotlin generates for an object in Java, it will actually result in the proper 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(); }

}


回答2:

The reason you are not getting any warning is because the android studio does not have mature lint check rules for Kotlin being used for android. Once toolkit team updates their lint check rules for kotlin with android, the warning will appear again.