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

前端之家收集整理的这篇文章主要介绍了java – Kotlin中对象字段中带有上下文的Android类前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在Kotlin中有一个具有上下文的对象类中的属性是否可以?在 Android中,将上下文相关对象放在静态字段中是一种不好的做法. Android工作室甚至突出显示它并发出警告,不像Kotlin那样没有警告.
示例对象:
  1. object Example {
  2. lateinit var context: Context
  3.  
  4. fun doStuff(){
  5. //..work with context
  6. }
  7. }

解决方法

由于对象是单例,因此它们只有一个静态实例.因此,如果您为它们提供了一个context属性,那么您仍然以静态方式存储Context.

这与将Context放在Java中的静态字段中具有完全相同的结果.

如果你编写Kotlin为Java中的对象生成的等效代码,它实际上会导致正确的lint错误

  1. public class Example {
  2.  
  3. // Do not place Android context classes in static fields; this is a memory leak
  4. // (and also breaks Instant Run)
  5. public static Context context;
  6.  
  7. // Do not place Android context classes in static fields (static reference to
  8. // Example which has field context pointing to Context); this is a memory leak
  9. // (and also breaks Instant Run)
  10. public static Example INSTANCE;
  11.  
  12. private Example() { INSTANCE = this; }
  13.  
  14. static { new Example(); }
  15.  
  16. }

猜你在找的Android相关文章