Skip to content

Instantly share code, notes, and snippets.

@eduardobape
Last active November 22, 2022 01:22
Show Gist options
  • Save eduardobape/0b8a6937d4f196f589396a2e45b4ad9b to your computer and use it in GitHub Desktop.
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)
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
}
@eduardobape
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment