https://kotlinlang.org logo
#getting-started
Title
# getting-started
m

MR3Y

10/05/2023, 7:40 PM
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

ephemient

10/05/2023, 7:50 PM
OkHttp
isn't a
HttpClientEngineFactory<T>
, it's a
HttpClientEngineFactory<OkHttpConfig>
, and it's possible the caller may use
!(T : OkHttpConfig)
m

MR3Y

10/05/2023, 8:03 PM
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

ephemient

10/05/2023, 8:04 PM
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

MR3Y

10/05/2023, 8:09 PM
Yeah, this works. this what I wanted actually since I don't care about the type in my dependent function's implementation. Thanks.