generics - 使用泛型类型设计类和接口
问题描述
我有以下接口映射并接受作为参数 aInsectTypesEntity
并返回 a 的对象和返回 a 的InsectDataModel
另一个对象List<InsectDataModel>
我正在尝试使用泛型来做到这一点,因为我想练习这个。
interface InsectInteractorMapper<T> {
fun map(insectTypesEntity: T): T
fun map(cursor: Cursor): List<T>
}
如果没有泛型,它将是这样的:
interface InsectInteractorMapper<InsectTypesEntity> {
fun map(insectTypesEntity: InsectTypesEntity): InsectDataModel
fun map(cursor: Cursor): List<InsectDataModel>
}
我试图让我的类使用接口的通用版本实现这一点,但是,我得到了许多相关的错误:
1) Return type is 'insectDataModel' which is not a subtype of overridden
public abstract fun map(insectTypesEntity: InsectTypesEntity): InsectTypeEntity defined in InsectInteractorMapper
2) Return type is 'List<InsectDataModel>' which is not a subtype of overridden
public abstract fun map(cursor: Cursor): List<InsectTypesEntity> defined in InsectInteractorMapper
实现接口的类
class InsectInteractorMapperImp: InsectInteractorMapper<InsectTypesEntity> {
override fun map(insectTypesEntity: InsectTypesEntity): InsectDataModel {
return InsectDataModel(
insectTypesEntity.friendlyName,
insectTypesEntity.scientificName,
insectTypesEntity.classification,
insectTypesEntity.imageAsset,
insectTypesEntity.dangerLevel)
}
override fun map(cursor: Cursor): List<InsectDataModel> {
val insectDataModelList: MutableList<InsectDataModel> = mutableListOf()
cursor.moveToFirst()
while(cursor.moveToNext()) {
InsectDataModel().let {
it.friendlyName = cursor.getString(cursor.getColumnIndexOrThrow(InsectContract.COLUMN_FRIENDLY_NAME))
it.scientificName = cursor.getString(cursor.getColumnIndexOrThrow(InsectContract.COLUMN_SCIENTIFIC_NAME))
it.dangerLevel = cursor.getInt(cursor.getColumnIndexOrThrow(InsectContract.COLUMN_DANGER_LEVEL))
insectDataModelList.add(it)
}
}
cursor.close()
return insectDataModelList.toList()
}
}
使用泛型正常工作的最佳方法是什么?
非常感谢您的任何建议,
==== UPDATE 修改了输入/输出差异的接口:
interface InsectInteractorMapper<in E, out M> {
fun map(insectTypesEntity: E): M
fun map(cursor: Cursor): List<M>
}
但是,当我尝试使用界面时收到警告:
unchecked assignment java.util.List to java.util.List<InsectDataModel> Reason insectDataModelMapper has raw type so result of map will be erased
当我这样使用它时:
insectInteractorMapper = new InsectInteractorMapperImp();
insectDataModelList = insectInteractorMapper.map(cursor);
解决方案
既然你想要一个in
类型和一个out
类型,你需要像这样声明它们:
interface InsectInteractorMapper<in T1, out T2> {
fun map(insectTypesEntity: T1): T2
fun map(cursor: Cursor): List<T2>
}
然后你的代码就可以工作了
推荐阅读
- python-3.x - 执行 tkinter 按钮而不点击它
- r - 从固定效应模型 (plm) 绘制交互项
- strapi - Strapi 是否允许 JSON 字段元素编辑
- linux - 在 Linux 中从 Twitter API 访问数据的问题 - 不断出现 curl:未指定 url?
- mysql - 为具有重叠 ID 的表创建视图
- reactjs - context api - 在上下文数据中循环
- excel - 文本到列,值内有分隔符
- matlab - 当矩阵在 MATLAB 中是 3D 时,如何只保留满足某些行假设的重复?
- c# - 通过启动过程传递变量的Powershell问题
- c - 如何使用 gcc 在 C 中编译自制头文件?