Last active
November 22, 2022 01:22
-
-
Save eduardobape/0b8a6937d4f196f589396a2e45b4ad9b to your computer and use it in GitHub Desktop.
Two different methods implementations for filtering elements of a list by a specific type (or class)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fun main() { | |
println(filterByType1<Boolean>(listOf(1, 2, "hola", true))) | |
println(listOf(1, 2, 3, "hola", false).filterIsInstance<Boolean>()) | |
println(filterByType2(listOf(10, 20, true, 10.5, "hello"), java.lang.Boolean::class.java)) | |
println(filterByType2(listOf(10, 20, true, 10.5, "hello", false), Boolean::class.javaObjectType)) | |
} | |
@Suppress("UNCHECKED_CAST") | |
inline fun <reified T> filterByType1(unfilteredList: List<*>): List<T> = unfilteredList.filter { it is T } as List<T> | |
fun <T> filterByType2(unfilteredList: List<*>, type: Class<T>): List<T> { | |
val filteredList = mutableListOf<T>() | |
@Suppress("UNCHECKED_CAST") | |
for (elem in unfilteredList) { | |
if (type.isInstance(elem)) filteredList.add(elem as T) | |
} | |
return filteredList | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Perfect explanation of how reified is and how it works: https://stackoverflow.com/questions/45949584/how-does-the-reified-keyword-in-kotlin-work