1

In my android project:

// Extension Properties
val Response<*>.errorResponse: ErrorResponse
    get() = ErrorUtils.parseError(this)

class TransportService {
    companion object {
        private val SERVICE_UNAVAILABLE_CODE = 503
        private val traderMonitorRestClient = RestClientFactory.createRestClient(TraderMonitorRestClient::class.java)
        private val serviceUnavailableErrorResponse: Response<*>


}

and here use extension property

class TradersViewModel(application: Application) : AndroidViewModel(application) {

  val errorResponse = response.errorResponse

}

nice it's work,

But if I move errorResponse inside class:

class TransportService {
    companion object {
        private val SERVICE_UNAVAILABLE_CODE = 503
        private val traderMonitorRestClient = RestClientFactory.createRestClient(TraderMonitorRestClient::class.java)
        private val serviceUnavailableErrorResponse: Response<*>

        private val TAG = TransportService::class.java.name

        val Response<*>.errorResponse: ErrorResponse
            get() = ErrorUtils.parseError(this)
    }
}

then I get compile error in use place:

val errorResponse = response.errorResponse

error:

Unresolved reference: errorResponse
Joffrey
  • 32,348
  • 6
  • 68
  • 100
Alexei
  • 14,350
  • 37
  • 121
  • 240

1 Answers1

3

This is because the errorResponse extension is only available in the context of the companion object of TransportService when you define it there.

If your extension function doesn't need the companion's properties or methods, there is no real reason to put the extension there. Don't be afraid of polluting the global scope. Technically, you're only defining this extension on your Response object.

That being said, if you really need the companion object's context for your extension function (e.g. if the body of your extension property uses some methods or properties of the companion), you can manually provide the context on the usage site this way:

val errorResponse = with(TransportService.Companion) { response.errorResponse }

This is not limited to companion objects, you just need to provide an instance of the class that contains the extension to with(instance).

Joffrey
  • 32,348
  • 6
  • 68
  • 100