2017-06-05 5 views
2

kotlinでネットワーク操作を実行するためにutilsを作成しようとしています。私はプライマリコンストラクタがCommandContextを取っている以下のコードを持っています。Koltinのstatic companionオブジェクトのインスタンス変数にアクセスする方法

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)) 
      } 
     } 
    } 
} 
関連する問題