Generics kotlin仿制药的使用;“在”中&引用;“出去”;继承
我计划使用基类从服务器下载一些数据:Generics kotlin仿制药的使用;“在”中&引用;“出去”;继承,generics,kotlin,Generics,Kotlin,我计划使用基类从服务器下载一些数据: abstract class Processor<out T : BaseEntity> { fun loadData() { val data = fetchFromBackend() saveData(data) } // here I'll define specific logic of saving data // and here is my Error Type parameter
abstract class Processor<out T : BaseEntity> {
fun loadData() {
val data = fetchFromBackend()
saveData(data)
}
// here I'll define specific logic of saving data
// and here is my Error Type parameter T is declared as 'out' but occurs in 'invariant' position in type T
abstract protected open fun saveData(data: T)
}
为了能够安全地将处理器的实现分配给基本类型,我正在使用outinT
泛型声明。但这会导致saveData(data:T)
方法出现问题。若我使用不变性,意味着在泛型声明之前并没有关键字,我将无法安全地将处理器的实现分配给基类型
有没有一种方法可以在不使用类强制转换的情况下实现这个类层次结构,或者实现这个层次结构的最佳方法是什么?这能满足您的需要吗
abstract class Processor<T : BaseEntity> {...}
val processor: EntityProcessor<out BaseEntity> = ...
抽象类处理器{…}
val处理器:EntityProcessor=。。。
谢谢你的帮助!您能解释一下in
out
在变量声明中是如何工作的吗。在这里,您可以调用processor.loadData()
(不涉及t
),但不能调用processor.saveData(something)
,因为它的t
位置错误,所以编译器不知道必须是哪种类型的something
。
abstract class Processor<T : BaseEntity> {...}
val processor: EntityProcessor<out BaseEntity> = ...