在Kotlin的对象字段中带有上下文的Android类

在Kotlin的对象类中有一个属性,它有一个上下文吗? 在Android中,将上下文相关的对象放在静态字段中是一个不好的做法。 Android工作室甚至突出显示它,并给出了一个警告,不像Kotlin没有警告。 示例对象:

object Example { lateinit var context: Context fun doStuff(){ //..work with context } } 

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

你没有得到任何警告的原因是因为 android工作室没有成熟的lint检查规则 ,用于Android的Kotlin。 一旦toolkit team使用android更新kotlin的lint check rules ,警告将再次出现。