I am working on an app that has 3 weather APIs and I want my user to be able to choose which one should be used. Each of those APIs has each own data format, so I wanted to create a function that creates proper interface and than wrapps it, so the result is something common, so that I could handle it the same way for each interface. So my code looks like that:
fun create(api: Apis): ApiDataSource = retrofitBuilder
.baseUrl(getBaseUrlFor(api))
.build()
.create(getInterfaceClassFor(api))
.convertWith(interfaceConverter)
}
fun Api1.convertWith(interfaceConverter: InterfaceConverter): CommonWeatherDataEntity = ...
private fun getInterfaceClass(api: Apis): Class<*> = when (api) {
Apis.Api1 -> Api1Interface::class.java
Apis.Api2 -> Api2Interface::class.java
}
However line after .create(...)
is highlighted red and error says "Unresolved reference". That's because create is returning Any!
What I don't understand (are generics obviously) is why the following code works fine:
fun Apis.createInterface(retrofitBuilder: Retrofit.Builder) =
retrofitBuilder.baseUrl(getBaseUrlFor(this))
.build()
.create(
when (this) {
Apis.Api1 -> Api1Interface::class.java
Apis.Api2 -> Api2Interface::class.java
}
).convertWith(interfaceConverter)
Because the type inferred for when(...)
is not Class<*>
, but Class<out X>
, where X
is the common supertype of Api1Interface
and Api2Interface
. So create
returns X
.
You should be able to see that by removing the return type for getInterfaceClass
and checking what the IDE shows.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.