Mervil
07/24/2020, 7:47 PMAlejandro Rios
07/24/2020, 7:50 PMMayank
07/24/2020, 8:08 PMval list = ArrayList<String>()
list.run {
// here receiver is this. You can think like you are in the ArrayList class itself so we can directly call add and remove methods
add("Hello")
add("World")
removeAt(0)
}
list.let {
// here receiver is it. You can think this like you have just renamed list to it. We would need to call methods on it as we would have called on list
it.add("Hello")
it.add("World")
it.removeAt(0)
}
run and let both returns the last line of block so in example below let would return 2
val value = list.let {
it.add("Hello")
2
}
print(value) //would print 2
in terms of receiver apply is same as run and also is same as let
The difference between apply and run OR also and let is that apply/also return the object on which they were called and run/let returns last line of the block
val value = list.also {
it.add("Hello")
2
}
print(value) //would print list
In above example we used also on list so value will be assigned to list no matter what last line of block is
Regarding when to use which operator you can have a look into this flowchart: https://medium.com/androiddevelopers/kotlin-standard-functions-cheat-sheet-27f032dd4326
I hope this helps you understand the scopesMervil
07/24/2020, 11:13 PMJakub Pi
07/25/2020, 2:50 AMl.map{it.value}
The it is just the default name. You can actually assign a name if you want.
this
comes from OOP. Within the context of an object, any method can refer to the instance on which the method was called by using this
. It's also possible to reference internal fields of the instance, so if there was a local variable named foo and a field with the same name, you could assign the field value using this.foo = foo
The biggest difference is that in cases where there is no name collision, everything on this
can be accessed directly without a prefix of this.
The "receiver" is the actual backing instance receiving the calls. When you use "it" it's always explicit, so it's a bit more verbose but avoids name collisions. The functions that use "this" allow you to use an concise, implicit style but you have to worry about naming conflicts in case both "this" and your local scope have functions or variables with the same name.
There is actually a third type of receiver which can delegate calls to the containing scope, which you would use in nested closures to allow implicit calls against elements one more more levels up. It's commonly seen in groovy, so you might see it if you are still using the old Gradle build scripts (not the kts ones).Mervil
07/25/2020, 2:55 AMJakub Pi
07/26/2020, 3:38 AMMervil
07/26/2020, 5:14 PMJakub Pi
07/27/2020, 1:27 AM