Kotlin 中的对象类中是否可以有一个具有上下文的属性?在 Android 中,将上下文相关对象放入静态字段中是一种不好的做法。 Android studio 甚至会突出显示它并发出警告,这与 Kotlin 不同,Kotlin 没有警告。
示例对象:
object Example {
lateinit var context: Context
fun doStuff(){
//..work with context
}
}
Since object
s 是单例,它们有一个静态实例。所以如果你给他们一个context
属性,您仍在存储Context
以静态的方式。
这将产生与放置完全相同的结果Context
在Java中的静态字段中。
如果您编写 Kotlin 生成的等效代码object
在 Java 中,它实际上会导致正确的 lint 错误:
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(); }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)