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

问题描述:

我正在尝试使用utils来执行kotlin中的网络操作。我有下面的代码主要构造函数采取CommandContext如何访问Koltin中的静态伴侣对象中的实例变量

我无法访问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)) 
      } 
     } 
    } 
} 

甲伴侣对象不是类的实例的一部分。 无法从协同对象访问成员,就像在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)) 
     } 
    } 
} 

您应该直接将参数传递给你的同伴目标函数:

class AsyncService { 

    companion object { 
     fun doGet(command: Command, context: Context, request: String) { 
      doAsync { 
       val jsonObj = java.net.URL(request).readText() 
       command.execute(JSONObject(jsonObj)) 
      } 
     } 
    } 
}