我在 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
不为空,因此此处使用 !!
并不安全。
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/