假设说我有两个模型类
open class Entity{
}
class EntityParcel : Entity(){
}
并与同伴方法的简单类的转换List<Entity>
,以List<EntityParcel>
class ConvertFactory{
companion object{
fun toParcel(e:Entity):EntityParcel{
return EntityParcel()
}
fun toParcel(list:List<Entity>):List<EntityParcel>{
val aList:ArrayList<EntityParcel> = ArrayList()
list.forEach{
aList.add(toParcel(it))
}
return aList
}
}
}
现在我正在尝试使用上面的类和方法和这样的泛型
class CustomClass<E:Entity,P:EntityParcel>{
fun someMethod(){
val eList:List<E> = emptyList()
val pList:List<P> = ConvertFactory.toParcel(eList)
}
}
我Type mismatch: inferred type is List<EntityParcel> but List<P> was expected
在行中收到编译器错误
val pList:List<P> = ConvertFactory.toParcel(eList)
通过定义P:EntityParcel
inCustomClass
并使toParcel
方法返回不可变,List<EntityParcel>
我认为这样的转换会得到处理。但看起来我在这里遗漏了一些东西。有没有合适的方法来做到这一点?非常感谢帮助。
编辑:假设该类的唯一目的CustomClass
是将给定List<Entity>
的List<EntityParcel>
. 同时,该类必须使用泛型来实现这种转换,因为我可能会使用同一个类的列表转换SomeOtherEntity
到一个列表SomeOtherEntityParcel
。通过这种方式,我只需要编写从实体复制到其包裹的内容,并抽象所有其他转换样板。
好吧,如果P
不是,EntityParcel
而是某个子类型,例如Nothing
(P:EntityParcel
允许),那么pList
isList<Nothing>
和 a的类型List<EntityParcel>
不适合。“正确的方法”在很大程度上取决于CustomClass
应该实际做什么。
此外,该类必须使用泛型来实现这种转换,因为我可能会使用相同的类将 SomeOtherEntity 列表转换为 SomeOtherEntityParcel 列表。通过这种方式,我只需要编写从实体复制到其包裹的内容,并抽象所有其他转换样板。(还添加了这个作为对问题的编辑)
就像是
abstract class CustomClass<E:Entity,P:EntityParcel>{
fun eToP(entity: E): P
fun listEToListP(list: List<E>): List<P> {
val aList: ArrayList<E> = ArrayList()
list.forEach {
aList.add(toParcel(it))
}
return aList
}
}
问题是,如果您对列表的元素进行了转换,则实际上不需要为列表实现转换,它在标准库中为map
:
fun listEToListP(list: List<E>): List<P> = list.map { eToP(it) }
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句