Skip to content

Instantly share code, notes, and snippets.

@fullmated
Created February 25, 2020 02:27
Show Gist options
  • Save fullmated/19a9c15feaa0a7b67c9b6ae61206d1e3 to your computer and use it in GitHub Desktop.
Save fullmated/19a9c15feaa0a7b67c9b6ae61206d1e3 to your computer and use it in GitHub Desktop.
// 参考: https://qiita.com/takusemba/items/f05ff78b39d40937901f
inline fun <reified T> List<T>.filterInstance(): List<T> {
val destination = mutableListOf<T>()
this.forEach {
//これはできない
//println(it::class)
if (it is T) destination.add(it)
}
return destination
}
fun main(args: Array<String>) {
// Your code here!
val nums = listOf(1, 2f, 3, 4f, "5", Pair(6, '6'), null)
val ints = nums.filterIsInstance<Number>() // [1, 3]
println(nums)
println(ints)
println(listOf(1, 2f, 3, 4f, "5", Pair(6, '6'), null).filterIsInstance<Int>())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment