sealed class Mission(open val quests: List<Quest>) {
sealed class SubMission(override val quests: List<Quest>) : Mission(quests) {
data class Mission1(override val quests: List<Quest>): SubMission(quests)
data class Mission2(override val quests: List<Quest>): SubMission(quests)
data class Mission3(override val quests: List<Quest>): SubMission(quests)
} }
I have this structure in my code and a List<Mission>
.
Then using a following function I would like the list to return an exact item that matches the class given in function.
private fun getMission(currentMissionClass: KClass<Mission>): Mission {}
So let's say I'm giving the function argument Mission.SubMission.Mission1()
and I expect the function to return the item from List<Mission>
that matches that exact class. Is there an easy and convenient way to do this in kotlin?
CodePudding user response:
filterIsInstance should work
private inline fun <reified T: Mission> getMission(
list: List<Mission>, currentMissionClass: Class<T>): List<T> {
return list.filterIsInstance<T>()
}
getMission(list, Mission1::class.java)