2

Let's say I have a piece of code like:

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
    }

Is there any particular reason why compiler doesn't infer that .max() can only yield an Int, and thus this should not be an error, or am I missing something? Kotlin's documentation proudly points out about Smart Casts, and I think this is a quite similar and easy inference to make?

1 Answer 1

4

That can’t be handled by smart casting, you're using a max() extension function which always returns a nullable type, Int? in your case:

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

The compiler does what this method signature suggests: it makes you handle the possible null. How should the compiler know wether max works as intended? It might be implemented wrongly.

The following, on the other hand, works thanks to smart casting:

val maxNeg: Int? = li.filter { it < 0 }.max()
if (maxNeg != null) {
    return maxNeg //Can be used as Int
}
Sign up to request clarification or add additional context in comments.

3 Comments

I understand it, but that's my point, there is no null possible :/
@dgan you’re right, it can’t be null. Have a look at the description of smart casting again and you will notice that the examples are different: kotlinlang.org/docs/reference/typecasts.html
@dgan: the compiler can’t be sure that max works as intended. It simply sees the return type which might be null

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.