Kotlin 从非具体化函数调用具体化函数
我有一个第三方服务,它公开了一个具体化的扩展功能。为了便于测试和封装,我想将此服务包装到一个接口实现对中 问题是我无法在我的应用程序中使用此函数,因为编译器告诉我:Kotlin 从非具体化函数调用具体化函数,kotlin,generics,kotlin-reified-type-parameters,Kotlin,Generics,Kotlin Reified Type Parameters,我有一个第三方服务,它公开了一个具体化的扩展功能。为了便于测试和封装,我想将此服务包装到一个接口实现对中 问题是我无法在我的应用程序中使用此函数,因为编译器告诉我: Cannot use 'T' as reified type parameter. Use a class instead. 结构如下: interface ThirdPartyService inline fun <reified T> ThirdPartyService.execute(): T interfa
Cannot use 'T' as reified type parameter. Use a class instead.
结构如下:
interface ThirdPartyService
inline fun <reified T> ThirdPartyService.execute(): T
interface Wrapper {
fun <T> execute(): T
}
class WrapperImpl(private val thirdPartyService: ThirdPartyService) : Wrapper {
override fun <T> execute(): T =
thirdPartyService.execute()
}
接口第三方服务
inline fun ThirdPartyService.execute():T
接口包装器{
fun execute():T
}
类wrapperpimpl(私有val thirdPartyService:thirdPartyService):Wrapper{
重写fun execute():T=
thirdPartyService.execute()
}
在这种情况下,调用thirdPartyService.execute()
会导致我上面提到的编译器问题
有没有办法克服这个问题?这个
使用类来代替什么。
实际上意味着什么?当您将一个类型标记为具体化时,您允许它在函数中的通常会被擦除的位置显式使用
但是,Wrapper.execute
函数中的类型T
没有具体化,这意味着它将在运行时被删除,因此无法“传递”到ThirdPartyService.execute
函数
您可以阅读更多关于具体化类型的信息
本质上,具有具体化类型的函数的全部要点在于它可以在运行时使用该类型。因此,在没有具体类型的情况下调用它没有任何意义,而且由于类型擦除,非具体化的
t
不是具体类型