如何解决对密封类子级列表进行排序的通用方法
我想将列表转换为从方法参数接收的类类型。
基本上,我想基于ClassA中存在的字段对列表进行排序。 该如何实现?
sealed class ParentClass
data class ClassA(fieldInClassType: Int) : ParentClass()
data class ClassB(fieldInClassType: Int) : ParentClass()
我有一个ClassA和ClassB的列表,我想创建一个通用的方法对它们进行排序。在我的旧代码中,我使用了when()
,但看起来很丑。
所以我试图用通用方法重构代码。这就是我现在拥有的
private fun <T: ParentClass>foo(data: List<T>,classType: Class<T>){
val list = data as classType
list.sortedBy{it.fieldInClassType}
}
解决方法
如果您使用的是密封类,则可以使用when
来确保您的代码涵盖所有潜在的子类。
sealed class ParentClass
data class ClassA(val fieldInClassType: Int) : ParentClass()
data class ClassB(val fieldInClassType: Int) : ParentClass()
fun foo(data: List<ParentClass>): List<ParentClass> {
return data.sortedBy {
when (it) {
is ClassA -> it.fieldInClassType
is ClassB -> it.fieldInClassType
}
}
}
fun main() {
val sorted = foo(listOf(ClassA(4),ClassB(1)))
sorted.forEach { println(it.javaClass) }
}
输出:
ClassB
ClassA
但是......
如果所有子类都具有该字段,请使用接口:
interface MyInterface {
val fieldInClassType: Int
}
sealed class ParentClass : MyInterface
data class ClassA(override val fieldInClassType: Int) : ParentClass()
data class ClassB(override val fieldInClassType: Int) : ParentClass()
fun foo(data: List<ParentClass>): List<ParentClass> {
return data.sortedBy { it.fieldInClassType }
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。