Why smartcast doesn't work after nullcheck

I am trying to come up with a code and wanted to create a class on day 10. I know that values ​​can be null, so I declared them null. At some point, I need to check if a value is assigned and do something with it. There is a problem. I check in advance through high != null, but in the next line I have to use !!to convince the compiler that it is actually null.

It seems that he cannot find the correct method compareTo, despite the fact that he first checks it. I guess this did not change my variable

private class Bot(val number: Int, var low: Int?, var high: Int?) {

  fun acceptValue(value: Int) {
    if (low == null && high == null) {
      high = value
    } else {
      if (high != null) {
        if (high!! > value) { //it doesn't compile, because appareantly, high is still not considered nonnull at this point
          low = value
        } else {
          low = high
          high = value
        }
      }
    }
  }
}

kotlin version is used 1.1.3-2

This is mistake? Am I doing something wrong?

+4
source share
3 answers

high != null high > value high = null, . , .

, :

val cHigh = high
if (cHigh != null) {
    if (cHigh > value) {
        ....
+3

high var, . , , .

:

, , , . , :

  • val - ;
  • val - , , . - , ;
  • var - , ;
  • var - ( ).

.let:

high?.let {
    if (it > value) {
        low = value
    } else {
      low = it
      high = value
    }
} ?: run {
    //high == null
}

: , NULL,

+5

, private:

private class Bot(val number: Int, 
                  private var low: Int?, 
                  private var high: Int?) {

    ...
}
0

Source: https://habr.com/ru/post/1683399/


All Articles