是否有更好的方法在列表中过滤null?

Kev*_*tel 0 null functional-programming casting kotlin

我这样做是为了过滤空值列表:

val myList: List<Any?> = [...]
myList.filter { it != null }.map { it!! }
myList.get(0).xxx // don't need to write "?."
Run Code Online (Sandbox Code Playgroud)

如果我不添加map,列表不会成为List<...>.有更优雅的方式吗?

mie*_*sol 6

使用filterNotNull如下:

val onlyPresent = myList.filterNotNull()
Run Code Online (Sandbox Code Playgroud)