智能投出 Arrow-kt 选项
Smart cast an Arrow-kt Option
我正在尝试从任何 Any 变量智能转换选项,以便我可以确定选项是否为空,但是 IDE 指示选项<*> 不能智能转换,因为它已声明在不同的模块中。
fun hasEmptyValue(column: Pair<String, Any>): Boolean = when {
column.second is Option<*> -> column.second.isEmpty()
else -> false
}
以下原因使 smartcast 对我有用:
fun hasEmptyValue(column: Pair<String, Any>): Boolean {
val second = column.second
return when (second) {
is Option<*> -> second.isEmpty() //Smart cast to arrow.core.Option<*>
else -> false
}
}
为什么不允许跨模块智能转换的解释在 Jetbrains 问题跟踪器上 here:
A smart cast is only valid when multiple accesses of the same property are guaranteed to return the same value. If the property being accessed is defined in a different module from the access location, the module containing the property can be recompiled separately from the module where it’s accessed, breaking the key requirement of the smart cast. Therefore, cross-module smart casts are not allowed.
David Rawson 展示了如何修复它,但没有解释为什么您的代码不起作用。
原因是 column.second
原则上可以 return 两次调用的不同值;即使 Pair#second
是一个 val
,它也可以有一个自定义的 getter 方法。
如果 Pair
在同一个模块中,编译器可以检查这一点,但对于其他模块则不会。
我正在尝试从任何 Any 变量智能转换选项,以便我可以确定选项是否为空,但是 IDE 指示选项<*> 不能智能转换,因为它已声明在不同的模块中。
fun hasEmptyValue(column: Pair<String, Any>): Boolean = when {
column.second is Option<*> -> column.second.isEmpty()
else -> false
}
以下原因使 smartcast 对我有用:
fun hasEmptyValue(column: Pair<String, Any>): Boolean {
val second = column.second
return when (second) {
is Option<*> -> second.isEmpty() //Smart cast to arrow.core.Option<*>
else -> false
}
}
为什么不允许跨模块智能转换的解释在 Jetbrains 问题跟踪器上 here:
A smart cast is only valid when multiple accesses of the same property are guaranteed to return the same value. If the property being accessed is defined in a different module from the access location, the module containing the property can be recompiled separately from the module where it’s accessed, breaking the key requirement of the smart cast. Therefore, cross-module smart casts are not allowed.
David Rawson 展示了如何修复它,但没有解释为什么您的代码不起作用。
原因是 column.second
原则上可以 return 两次调用的不同值;即使 Pair#second
是一个 val
,它也可以有一个自定义的 getter 方法。
如果 Pair
在同一个模块中,编译器可以检查这一点,但对于其他模块则不会。