空数组kotlin上的类型推断

空数组kotlin上的类型推断,kotlin,nullable,Kotlin,Nullable,假设我有一段代码,比如: fun temp2 (li : MutableList<Int>):Int { if (li.isEmpty()) return 0 val pos=li.filter { it>0 } val neg=li.filter { it<0 } if (pos.isEmpty() && neg.isNotEmpty()){ // this gives compiling error

假设我有一段代码,比如:

fun temp2 (li : MutableList<Int>):Int {
    if (li.isEmpty()) return 0
    val pos=li.filter { it>0 }
    val neg=li.filter { it<0 }

    if (pos.isEmpty() && neg.isNotEmpty()){

        // this gives compiling error because Required: Int, Found: Int?
        // But I just checked one line higher that neg is Not Empty, so there (at least I guess) 
       // no possible way to have an NPE?
        //return neg.max()
          return neg.max()!! //this works fine
    }
fun temp2(li:MutableList):Int{
if(li.isEmpty())返回0
val pos=li.filter{it>0}

val neg=li.filter{it智能强制转换无法处理,您正在使用一个
max()
扩展函数,该函数在您的情况下总是返回一个可为空的类型,
Int?

public fun <T : Comparable<T>> Iterable<T>.max(): T? 

我理解这一点,但这是我的观点,不可能有空值:/@dgan你是对的,它不可能是空的。再看一下智能强制转换的描述,你会注意到示例是不同的:@dgan:编译器不能确保max按预期工作。它只看到可能为空的返回类型
val maxNeg: Int? = li.filter { it < 0 }.max()
if (maxNeg != null) {
    return maxNeg //Can be used as Int
}