在 Kotlin 列表中使用泛型时键入不匹配错误

AgilanBTDW

假设说我有两个模型类

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:EntityParcelinCustomClass并使toParcel方法返回不可变,List<EntityParcel>我认为这样的转换会得到处理。但看起来我在这里遗漏了一些东西。有没有合适的方法来做到这一点?非常感谢帮助。

编辑:假设该类的唯一目的CustomClass是将给定List<Entity>List<EntityParcel>. 同时,该类必须使用泛型来实现这种转换,因为我可能会使用同一个类的列表转换SomeOtherEntity到一个列表SomeOtherEntityParcel通过这种方式,我只需要编写从实体复制到其包裹的内容,并抽象所有其他转换样板。

阿列克谢·罗曼诺夫

好吧,如果P不是,EntityParcel而是某个子类型,例如NothingP:EntityParcel允许),那么pListisList<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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章