为什么这是正确的,下面的一个是错误的?
更正一
fun main () {
AppModule().provideHttpClient(CIO)
}
不对
fun <T : HttpClientEngineConfig> provideHttpClient(engineFactory: HttpClientEngineFactory<T> = CIO): HttpClient
型失配
要求:HttpClientEngineFactory
发现:首席信息干事
CIO的定义为:
public object CIO : HttpClientEngineFactory<CIOEngineConfig> {
init {
addToLoader()
}
override fun create(block: CIOEngineConfig.() -> Unit): HttpClientEngine =
CIOEngine(CIOEngineConfig().apply(block))
override fun toString(): String = "CIO"
}
发布于 2022-05-18 11:20:52
泛型方法的语义是“我与任何类型一起工作”,因此泛型方法的类型参数由调用方指定--调用方可以决定什么是T
。因此,对于调用方可能传入的任何HttpClientEngineFactory<T>
,指定为被调用方的默认值必须与T
兼容。
在这里,使用CIO
不起作用,因为您正在强迫T
成为CIOEngineConfig
。
想象一下,如果允许CIO
的默认值,而调用方允许这样做,会发生什么情况:
AppModule().provideHttpClient<SomeOtherEngineConfig>()
从声明provideHttpClient
的方式来看,这应该是可能的--我正在为泛型类型参数T
传递SomeOtherEngineConfig
,而且由于engineFactory
参数具有默认值,所以不需要传递任何其他参数。但是当实际运行时,CIO
的默认值将用于HttpClientEngineFactory<SomeOtherEngineConfig>
类型的参数!
解决这个问题很容易:只需声明另一个非泛型的provideHttpClient
重载:
fun provideHttpClient(): HttpClient = provideHttpClient(CIO)
https://stackoverflow.com/questions/72287934
复制相似问题