Tag: 过滤器可以为

Kotlin:消除List中的空值(或其他功能转换)

问题 在Kotlin型系统中解决这种零安全限制的惯用方法是什么? val strs1:List<String?> = listOf("hello", null, "world") // ERROR: Type Inference Failed: Expected Type Mismatch: // required: List<String> // round: List<String?> val strs2:List<String> = strs1.filter { it != null } 这个问题不仅仅是消除空值,而且是为了使类型系统认识到通过转换从集合中删除了空值。 我不想循环,但如果这是最好的办法。 变通 以下编译,但我不知道这是做到这一点的最好方法: fun <T> notNullList(list: List<T?>):List<T> { val accumulator:MutableList<T> = mutableListOf() for (element in list) { if (element != null) { accumulator.add(element) […]