7

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
    }
}
3
  • 4
    in java it is a bad practice no ... it is related to Android not java ... which implicates that it is also bad in Kotlin ... Commented May 23, 2017 at 12:29
  • also there are different Contexts ... Application, Activity, Service ... storing Application's Context is "less bad"(you can do it better but there should be no Context leaks) than storing Activity or Service context Commented May 23, 2017 at 12:31
  • Yeah, my bad. Changed it to Android. Commented May 23, 2017 at 12:33

2 Answers 2

8

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

}
Sign up to request clarification or add additional context in comments.

3 Comments

But why there is no warning then?
Because google forgot or it is hard to find such situation with Kotlin's "object"... feel free to fill bug report
Indeed, they probably just haven't added this lint check for Kotlin objects yet.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.