Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access instance variable in static companion object in Kotlin

Tags:

kotlin

I am trying to make utils for performing network operations in kotlin. I have below code where the primary constructor is taking Command and Context.

I am unable to access command variable in command.execute(JSONObject(jsonObj)), getting below error. I am not sure what is causing an issue?

Unresolved reference: command

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))
            }
        }
    }
}
like image 276
N Sharma Avatar asked Jun 05 '17 09:06

N Sharma


2 Answers

A companion object is not part of an instance of a class. You can't access members from a companion object, just like in Java you can't access members from a static method.

Instead, don't use a companion object:

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

    fun doGet(request: String) {
        doAsync {
            val jsonObj = java.net.URL(request).readText()
            command.execute(JSONObject(jsonObj))
        }
    }
}
like image 115
nhaarman Avatar answered Sep 19 '22 01:09

nhaarman


You should pass arguments directly to your companion object function:

class AsyncService {

    companion object {
        fun doGet(command: Command, context: Context, request: String) {
            doAsync {
                val jsonObj = java.net.URL(request).readText()
                command.execute(JSONObject(jsonObj))
            }
        }
    }
}
like image 43
AlexTa Avatar answered Sep 19 '22 01:09

AlexTa