在Kotlin中有一个具有上下文的对象类中的属性是否可以?在
Android中,将上下文相关对象放在静态字段中是一种不好的做法. Android工作室甚至突出显示它并发出警告,不像Kotlin那样没有警告.
示例对象:
示例对象:
- object Example {
- lateinit var context: Context
- fun doStuff(){
- //..work with context
- }
- }
解决方法
由于对象是单例,因此它们只有一个静态实例.因此,如果您为它们提供了一个context属性,那么您仍然以静态方式存储Context.
这与将Context放在Java中的静态字段中具有完全相同的结果.
如果你编写Kotlin为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(); }
- }