在Kotlin的对象类中有一个属性,它有一个上下文吗?在Android中,将上下文相关对象放在静态字段中是一种不好的做法。 Android工作室甚至突出显示它并发出警告,不像Kotlin那样没有警告。 示例对象:
object Example {
lateinit var context: Context
fun doStuff(){
//..work with context
}
}
答案 0 :(得分:8)
由于object
是单例,因此它们只有一个静态实例。因此,如果您为他们提供context
属性,那么您仍然以静态方式存储Context
。
这与将Context
置于Java中的静态字段中具有完全相同的结果。
如果您编写Kotlin在Java中为object
生成的等效代码,它实际上会导致正确的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(); }
}
答案 1 :(得分:1)
你没有得到任何警告的原因是,因为对于用于Android的Kotlin,android studio 没有成熟的lint检查规则。一旦toolkit team
使用android为kotlin更新lint check rules
,警告将再次出现。