Avatar ·

When to use run, let, apply, also and with in Kotlin? Examples and explanation

Hello everyone! I just started learning Kotlin after Java, and the scope functions (run, let, apply, also and with) really confused me. I read the documentation but still don't understand when to use which one. For example, I often see code like this: ```kotlin val numbers = mutableListOf("one", "two", "three") numbers.let { println(it) } numbers.apply { add("four") } numbers.run { println("Size: $size") } ``` But why can't I just write `println(numbers)` or `numbers.add("four")`? What's the difference between `let` and `apply`? And why do we need `also`? I also tried to initialize an object with configuration: ```kotlin val person = Person().apply { name = "John" age = 30 } ``` This works, but the same can be done with `with`: ```kotlin val