Android类在Kotlin的对象字段中具有上下文 [英] Android class with context in object field in Kotlin

查看:493
本文介绍了Android类在Kotlin的对象字段中具有上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Kotlin的对象类中拥有一个具有上下文的属性可以吗?在Android中,将上下文相关的对象放在静态字段中是一种不好的做法. Android Studio甚至会高亮显示它并发出警告,这与Kotlin不同,后者没有警告. 示例对象:

Is it ok to have a property in object class in Kotlin that has a context in it? In Android it is a bad practice to put context related objects in static fields. Android studio even highlights it and gives a warning unlike Kotlin where there is no warning. Example object:

object Example {
    lateinit var context: Context

    fun doStuff(){
        //..work with context
    }
}

推荐答案

由于object是单例,因此它们具有单个静态实例.因此,如果为它们提供context属性,您仍将以静态方式存储Context.

Since objects are singletons, they have a single static instance. So if you give them a context property, you're still storing a Context in a static way.

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

This will have the exact same consequences as putting a Context in a static field in Java.

如果您用Java编写Kotlin为object生成的等效代码,则实际上会导致适当的皮棉错误:

If you write the equivalent code that Kotlin generates for an object in Java, it will actually result in the proper lint errors:

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类在Kotlin的对象字段中具有上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆