Android类在Kotlin的对象字段中具有上下文 [英] Android class with context in object field in Kotlin
问题描述
在Kotlin的对象类中拥有一个具有上下文的属性可以吗?在Android中,将上下文相关的对象放在静态字段中是一种不好的做法. Android Studio甚至会高亮显示它并发出警告,这与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
}
}
推荐答案
由于object
是单例,因此它们具有单个静态实例.因此,如果为它们提供context
属性,您仍将以静态方式存储Context
.
Since object
s 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.
与将Context
放入Java的静态字段中具有完全相同的结果.
This will have the exact same consequences as putting a Context
in a static field in Java.
如果您用Java编写Kotlin为object
生成的等效代码,则实际上会导致适当的皮棉错误:
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(); }
}
这篇关于Android类在Kotlin的对象字段中具有上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!