如何在Koltin中访问静态伴随对象中的实例变量

N S*_*rma 4 kotlin

我正在尝试使用utils来执行网络操作kotlin.我有以下代码,主要构造函数正在CommandContext.

我无法访问命令变量command.execute(JSONObject(jsonObj)),低于错误.我不确定是什么原因造成的?

未解决的参考:命令

class AsyncService(val command: Command, val context: Context) {

    companion object {
        fun doGet(request: String) {
            doAsync {
                val jsonObj = java.net.URL(request).readText()
                command.execute(JSONObject(jsonObj))
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

nha*_*man 7

伴随对象不是类实例的一部分.您无法从协同对象访问成员,就像在Java中一样,您无法从静态方法访问成员.

相反,不要使用伴侣对象:

class AsyncService(val command: Command, val context: Context) {

    fun doGet(request: String) {
        doAsync {
            val jsonObj = java.net.URL(request).readText()
            command.execute(JSONObject(jsonObj))
        }
    }
}
Run Code Online (Sandbox Code Playgroud)