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
}
}
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 theirlint check rules
for kotlin with android, the warning will appear again.Since
object
s are singletons, they have a single static instance. So if you give them acontext
property, you're still storing aContext
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: