如何正确检查可空中缀接收器上的空值?
How do I properly check for null on nullable infix receivers?
我有一个 Kotlin 中缀函数被这样删掉了:
private fun statementMeetsConditions(policy: PolicyStatement, per: PolicyEnforcementRequest): Boolean {
return policy.conditions areMetBy per.attributes
}
private infix fun JsonNode?.areMetBy(attributes: Map<String, String>): Boolean {
if (this == null) return true //no conditions, so we pass
TODO("Condition-based policies not implemented")
}
在运行时,policy.conditions
为空。
我原以为 (this == null)
的计算结果为真,但是当中缀函数命中 TODO
.
时,我触发了运行时异常
这些都是 class 上的成员函数——所以我怀疑 "this" 正在评估 class 的实例(not null),而不是我期待的 JsonNode?
。如何确保我引用的是 JsonNode?
而不是 class?
null 检查是正确的,在这种情况下它检查可为 null 的 JsonNode?
接收器是正确的。
然而,Kotlin 中的 TODO
方法是一个爆炸性的待办事项,因为它总是在被击中时抛出 NotImplementedException
。这就是允许编译此代码的原因,即使并非所有分支 return 方法中的 Boolean
值。
NullNode
(jackson-databind-javadoc) 不是 null
;-) NullNode
实际上是它自己的类型......所以你可能更想检查那个类型相反...
检查 this
是否 null
以您期望的方式对 infix
函数起作用,即使这些扩展函数包含在 class.[=20 中=]
因此,要检查您的 policy.conditions
是否包含 NullNode
您可能宁愿将条件更改为以下内容:
if (this is NullNode) return true
这其实有点棘手。请注意条件值是 "null"
而不是 null
。这是因为
toString()
of ValueNode
调用 asText()
of NullNode
which returns a String
of value "null", 所以接收者 JsonNode?
实际上一直都不是空的。
因此,正如 Roland 所说,您必须检查接收方是否为 NullNode
类型。
我有一个 Kotlin 中缀函数被这样删掉了:
private fun statementMeetsConditions(policy: PolicyStatement, per: PolicyEnforcementRequest): Boolean {
return policy.conditions areMetBy per.attributes
}
private infix fun JsonNode?.areMetBy(attributes: Map<String, String>): Boolean {
if (this == null) return true //no conditions, so we pass
TODO("Condition-based policies not implemented")
}
在运行时,policy.conditions
为空。
我原以为 (this == null)
的计算结果为真,但是当中缀函数命中 TODO
.
这些都是 class 上的成员函数——所以我怀疑 "this" 正在评估 class 的实例(not null),而不是我期待的 JsonNode?
。如何确保我引用的是 JsonNode?
而不是 class?
null 检查是正确的,在这种情况下它检查可为 null 的 JsonNode?
接收器是正确的。
然而,Kotlin 中的 TODO
方法是一个爆炸性的待办事项,因为它总是在被击中时抛出 NotImplementedException
。这就是允许编译此代码的原因,即使并非所有分支 return 方法中的 Boolean
值。
NullNode
(jackson-databind-javadoc) 不是 null
;-) NullNode
实际上是它自己的类型......所以你可能更想检查那个类型相反...
检查 this
是否 null
以您期望的方式对 infix
函数起作用,即使这些扩展函数包含在 class.[=20 中=]
因此,要检查您的 policy.conditions
是否包含 NullNode
您可能宁愿将条件更改为以下内容:
if (this is NullNode) return true
这其实有点棘手。请注意条件值是 "null"
而不是 null
。这是因为
toString()
of ValueNode
调用 asText()
of NullNode
which returns a String
of value "null", 所以接收者 JsonNode?
实际上一直都不是空的。
因此,正如 Roland 所说,您必须检查接收方是否为 NullNode
类型。