kotlincastingpartitioning

How to partition and typecast a List in 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}

My question would be - is there's an idiomatic way to partition iterable by class and typecast it those partitioned parts if needed.


Solution

  • 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) }