【发布时间】:2020-01-30 13:11:08
【问题描述】:
在下面的示例中,我编写了简单的装饰器扩展,它可以捕获异常并在任何错误时返回 null。问题是num1 和num2 类型被推断为R? 而不是Double?:
val <R> (()->R).nothrow: (()->R?) get() = { try { invoke() } catch(ex: Throwable) { null } }
fun main() {
val num1 = "42"::toDouble.nothrow()
println(num1)
val num2 = "english"::toDouble.nothrow()
println(num2)
}
程序输出为:
42.0
null
但是当我写的时候
num1!! + 3.14
我得到错误:
Unresolved reference. None of the following candidates is applicable because of receiver type mismatch
候选人都是plus存在的运营商。
nothrow扩展的反编译java代码如下:
@NotNull
public static final Function0 getNothrow(@NotNull Function0 $this$nothrow) {
int $i$f$getNothrow = 0;
Intrinsics.checkParameterIsNotNull($this$nothrow, "$this$nothrow");
return (Function0)(new Function0($this$nothrow) {
// $FF: synthetic field
final Function0 $this_nothrow;
@Nullable
public final Object invoke() {
Object var1;
try {
var1 = this.$this_nothrow.invoke();
} catch (Throwable var3) {
var1 = null;
}
return var1;
}
public {
this.$this_nothrow = var1;
}
});
}
为什么会这样?
编辑
问题似乎出在扩展属性上:
【问题讨论】:
标签: java generics kotlin extension-methods