kotlin - 如何避免 Kotlin 字段中的冗余空检查(FindBugs 警告)

标签 kotlin findbugs

我在 Kotlin 类中归档了 bytes:

var bytes: ByteArray? = null
    get() = when {
        field != null -> Arrays.copyOf(field, field!!.size)
        else -> field
    }
    set(value) {
        field = when {
            value != null -> Arrays.copyOf(value, value.size)
            else -> null
        }
    }

为什么在第 3 行必须有一个 !! 运算符来表示 field

没有!!想法显示:

Smart cast to 'ByteArray' is impossible, because 'field' is a mutable property that could have been changed by this time

条件(field != null) 确保 if 主体(右侧)中的字段为 null。或不?或者可以同时将其重新分配为null?这怎么可能?

   

使用上面的代码 FindBugs 发出警告:

Redundant nullcheck of com.xy.Some.bytes which is known to be null in com.xy.Some.getBytes()

This method contains a redundant check of a known null value against the constant null.

http://findbugs.sourceforge.net/bugDescriptions.html#RCN_REDUNDANT_NULLCHECK_OF_NULL_VALUE

最佳答案

bytes 是一个 var ,它是可变的,并且可以在空检查后更改(可能在其他线程上)。您无法保证 bytes 不为空,因此此处使用 !! 并不安全。

Official explanation :

Note that smart casts do not work when the compiler cannot guarantee that the variable cannot change between the check and the usage. More specifically, smart casts are applicable according to the following rules:

  • val local variables - always;
  • val properties - if the property is private or internal or the check is performed in the same module where the property is declared. Smart casts aren't applicable to open properties or properties that have custom getters;
  • var local variables - if the variable is not modified between the check and the usage and is not captured in a lambda that modifies it;
  • var properties - never (because the variable can be modified at any time by other code).

解决方法之一是使用 let:

get() = field?.let { Arrays.copyOf(it, it.size) } ?: field

建议阅读:In Kotlin, what is the idiomatic way to deal with nullable values, referencing or converting them

关于kotlin - 如何避免 Kotlin 字段中的冗余空检查(FindBugs 警告),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45811956/

相关文章:

kotlin - Kotlin,Jackson:无法在主要构造函数中注释@JsonCreator

ant - FindBugs 使用 Ant 排除过滤器

java - findbugs 消息 : Method call passes null for unconditionally dereferenced parameter

gradle - 如何使用 Findbugs omitVisitors?

android - 如何将带有事件总线的逻辑放入 Kotlin 的演示器中

android - 未调用 Onesignal 远程通知接收方法

android - 使用实时数据时如何在 Android 中链接转换?

java - FindBugs 不会提示枚举中的不可序列化字段

java - 是否有开源插件可以根据 Findbugs Report 在 JIRA 中标记问题?

android - 用数据库中的不同对象填充数组