apply is? like, I have this code
fun main() {
println("Hello, world!!!")
var a = 3
var b = 5
var c = 0
c = a.apply { a to c}
b = a.also { a to b }
print("$a $b $c")
}
but both of them result in c = 3
Hi. Documentation for that here: https://kotlinlang.org/docs/reference/scope-functions.html In short: both are scope function and both will return original object (a in your case) Technical difference is in lambda: receiver parameter ( this ) will be in apply lambda scope and usual parameter (implicitly can be called as it ) will be in also lambda. In terms of practical difference - apply usually used to change object itself if that not possible in the constructor. Bad and outdated example is: val list = mutableListOf<Int>().apply { add(1) //can be this.add(1) add(2) } also is usually used to do something with object (store it, print it, etc): val something = foo().also { println(it) }
Back to your example: in both cases apply and also will do nothing :) (a to c or a to b will just create pair of two ints but it will not be stored anywhere) So technically your example is something like this but with extra steps: fun main() { println("Hello, world!!!") var a = 3 var b = 5 var c = 0 c = a // c = 3 a to c // will do nothing b = a // b = 3 a to b //will do nothing print("$a $b $c") }
Обсуждают сегодня