gpt4 book ai didi

kotlin - Kotlins的真正意图还在于示波器功能

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

我在问自己,语言设计者在scope函数后面的意图是什么,以及是否几乎每个人都在滥用它。

如果您在堆栈溢出此处搜索Kotlins范围函数的示例,那么您将得到以下可接受的答案:https://stackoverflow.com/a/45977254/5122729
also { }的给定答案是

also - use it when you want to use apply, but don't want to shadow this

class FruitBasket { private var weight = 0

fun addFrom(appleTree: AppleTree) {
val apple = appleTree.pick().also { apple ->
this.weight += apple.weight
add(apple)
}
...
}
...
fun add(fruit: Fruit) = ... }

Using apply here would shadow this, so that this.weight would refer to the apple, and not to the fruit basket.



这也是我经常看到的用法。但是,如果我看看 kotlinlang.org的文档,他们显然会说:

also is good for performing some actions that take the context object as an argument. Use also for additional actions that don't alter the object, such as logging or printing debug information. Usually, you can remove the calls of also from the call chain without breaking the program logic.



从该 Angular 来看,给定的示例将是错误的,因为如果将其删除,则会破坏程序逻辑。对我来说, also是Java的 peek( doc),它在那里,但是不应该用于生产程序逻辑。

有人可以启发我吗?

最佳答案

在Reddit上对该主题进行了较长的讨论后,文档的调整方式如下:

Usually, you can remove the calls of also from the call chain without breaking the program logic.



去掉了。参见相应的PR: https://github.com/JetBrains/kotlin-web-site/pull/1676

关于kotlin - Kotlins的真正意图还在于示波器功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61367281/

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