I'm asking myself what the language designers intention behind the also scope
function was and if almost everyone is misusing it.
If you search here on stack overflow for examples of Kotlins scope functions, you'll end up with this accepted answer: https://stackoverflow.com/a/45977254/5122729
The given answer for also { }
is
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.
That's also the usage I see quite often. But if I have a look into the documentation at kotlinlang.org, they are clearly saying:
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.
From that point of view, the given example would be wrong as it would break the program logic if it is removed. For me, also
is kind of Javas peek
(doc), which is there, but should not be used for productive program logic.
Can someone enlighten me?