如何在Kotlin中对列表进行分区和类型转换 [英] How to partition and typecast a List in Kotlin
本文介绍了如何在Kotlin中对列表进行分区和类型转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Kotlin中,我可以:
In Kotlin I can:
val (specificMembers, regularMembers) = members.partition {it is SpecificMember}
据我所知我不能做类似的事情:
However to my knowledge I can not do something like:
val (specificMembers as List<SpecificMember>, regularMembers) = members.partition {it is SpecificMember}
我的问题是-是否有一种惯用的方法来按类对iterable进行分区,并在需要时将这些已分区的部分类型转换.
My question would be - is there's an idiomatic way to partition iterable by class and typecast it those partitioned parts if needed.
推荐答案
partition
函数将返回Pair<List<T>, List<T>>
,其中T
是Iterable
的通用类型.您可以使用以下方法再次转换分区值: let
:
The partition
function will return a Pair<List<T>, List<T>>
with T
being the generic type of your Iterable
. You can transform the partitioned values again using e.g. let
:
val (specificMembers, regularMembers) = lists
.partition { it is SpecificMember }
.let { Pair(it.first as List<SpecificMember>, it.second) }
这篇关于如何在Kotlin中对列表进行分区和类型转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文