Question about generics, I've function like this: ...
# getting-started
m
Question about generics, I've function like this:
Copy code
expect fun <T : HttpClientEngineConfig> getEngineFactory(): HttpClientEngineFactory<T>
where
HttpClientEngineFactory
is defined as:
Copy code
public interface HttpClientEngineFactory<out T : HttpClientEngineConfig>
and on Jvm actual implementation is:
Copy code
actual fun <T : HttpClientEngineConfig> getEngineFactory(): HttpClientEngineFactory<T> {
    return OkHttp
}
where
OkHttp
is defined as:
Copy code
public object OkHttp : HttpClientEngineFactory<OkHttpConfig>
and for
OkHttpConfig
:
Copy code
public class OkHttpConfig : HttpClientEngineConfig
the problem is that the actual implementation doesn't compile because of type mismatch, required:
HttpClientEngineFactory<T>
found:
OkHttp
I can do:
Copy code
return OkHttp as HttpClientEngineFactory<T>
but I want to understand what is the problem here and if there is a better solution than the Unchecked cast
e
OkHttp
isn't a
HttpClientEngineFactory<T>
, it's a
HttpClientEngineFactory<OkHttpConfig>
, and it's possible the caller may use
!(T : OkHttpConfig)
m
I've control over where it can be called (actually it is called only in one place in a function's implementation), does that make it safe to cast it to
HttpClientEngineFactory<T>
?
e
IMO it's more accurate to write
Copy code
fun getEngineFactory(): HttpClientEngineFactory<*>
since the caller doesn't get to choose the type
thank you color 1
👍 1
m
Yeah, this works. this what I wanted actually since I don't care about the type in my dependent function's implementation. Thanks.