为什么在执行nullcheck后Smartcast无法正常工作 [英] Why does Smartcast not work after nullcheck

查看:68
本文介绍了为什么在执行nullcheck后Smartcast无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试代码的出现,并希望在第10天创建一个类.我知道这些值可以为null,因此我将其声明为可为空.在某个时候,我需要检查是否已分配该值并对其进行处理. 问题来了.我通过high != null进行了事先检查,但是在接下来的一行中,我必须使用!!来使编译器确信它实际上是空的.

I'm attempting advent of code and wanted to create a class for day 10. I know that the values can be null, so I declared them as nullable. At some point, I need to check whether the value is assigned and do something with it. There comes the issue. I check beforehand via high != null, but in the line that follows, I have to use !! to convince the compiler that it actually is null.

尽管先进行空检查,它似乎仍找不到正确的compareTo方法.我想,它没有智能广播我的变量

It seems that it can't find the proper compareTo method, despite nullchecking it first. I guess, it didn't smartcast 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版本是1.1.3-2

the kotlin-version is use is 1.1.3-2

那是个错误吗?我在做错什么吗?

Is that a bug? Am I doing something wrong?

推荐答案

high != nullhigh > value之间,另一个线程可以执行high = null,从而使空检查无效.所以这是预期的行为.

Between high != null and high > value another thread could do high = null, invalidating the null check. So this is the expected behavior.

解决此问题的方法是使用无法在外部更改的临时变量:

The way to solve this is to use a temporary variable which cannot be externally changed:

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

这篇关于为什么在执行nullcheck后Smartcast无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆