Kotlin filterIsInstance filterNotNull forEach
Kotlin
fun main(args: Array<String>) {
val i1 = MyItem(1, 1)
val i2: MyItem? = null
val i3: Int = 3
val i4 = "4"
val i5 = null
val i6 = MyItem(6, 6)
val list = mutableListOf<Any?>(i1, i2, i3, i4, i5, i6)
list.filterIsInstance(MyItem::class.java).forEach {
println(it)
}
println("---")
list.filterNotNull().forEach {
println(it)
}
}
class MyItem {
private var id = -1
private var pos = -1
constructor(id: Int, pos: Int) {
this.id = id
this.pos = pos
}
override fun toString(): String {
return "id=${id} pos=${pos}"
}
}
id=1 pos=1
id=6 pos=6
id=1 pos=1
3
4
id=6 pos=6