2017-06-05 67 views
2

我正在嘗試使用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)) 
      } 
     } 
    } 
} 

回答

6

甲伴侶對象不是類的實例的一部分。 無法從協同對象訪問成員,就像在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)) 
     } 
    } 
} 
3

您應該直接將參數傳遞給你的同伴目標函數:

class AsyncService { 

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