Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android class with context in object field in Kotlin

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
    }
}
like image 671
Arnis Shaykh Avatar asked May 23 '17 12:05

Arnis Shaykh


2 Answers

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

}
like image 188
zsmb13 Avatar answered Sep 26 '22 07:09

zsmb13


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.

like image 41
erluxman Avatar answered Sep 24 '22 07:09

erluxman