gpt4 book ai didi

kotlin - Kotlin:关于实例方法与扩展功能的 `tailrec`

转载 作者:行者123 更新时间:2023-12-02 13:18:26 27 4
gpt4 key购买 nike

在下面的代码中,我看到一个警告no tail calls found,但是当作为扩展函数编写时,同一函数没有该警告。现在我很困惑我的IDE是错误的,还是我的Extension方法实际上不是尾部递归的,还是编译器处理实例方法与Extension函数之间的区别?
enter image description here

最佳答案

作为第二个警告

Recursive call is not a tail call​



表示此调用是递归的,但不是尾部调用。

这是因为正在使用不同的实例作为目标( next而不是 this)来调用该函数,因此 tailrec在这种情况下实际上没有效果。如果将目标替换为 this,则编译器将停止发出任何警告。

我假设扩展函数编译时没有任何警告,因为它们被编译为静态(即非实例)函数,其中目标只是另一个参数,这意味着转换后的代码看起来(大致)类似于
@Nullable
public static final SLLNode2 getNodeForValue2(@NotNull SLLNode2 $this$getNodeForValue2, int valToFind) {
Intrinsics.checkParameterIsNotNull($this$getNodeForValue2, "$this$getNodeForValue2");
if ($this$getNodeForValue2.getValue() == valToFind) {
return $this$getNodeForValue2;
} else {
SLLNode2 var10000 = $this$getNodeForValue2.getNext();
return var10000 != null ? getNodeForValue2(var10000, valToFind) : null;
}
}

其中很明显包含一个递归的尾调用。

但是,我不确定这种区分是故意的,因为扩展功能的编译方式应该是实现细节,而实例函数示例应该等效地可以优化。

编辑:看来这实际上是 bug

关于kotlin - Kotlin:关于实例方法与扩展功能的 `tailrec`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61453849/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com