July 2018
Intermediate to advanced
400 pages
12h 14m
English
The also function works very similarly to the let function. Just like let, also passes the receiver you call it on as an argument to a lambda you provide. But there is one major difference between let and also: also returns the receiver, rather than the result of the lambda.
This makes also especially useful for adding multiple side effects from a common source. In the example below, also is called twice to organize two different operations: One prints the filename, and the other assigns a variable, fileContents, with the contents of the file.
var fileContents: List<String>
File("file.txt")
.also {
print(it.name)
}.also {
fileContents = it.readLines()
}
}
Since also returns the receiver instead of the result of the lambda, ...
Read now
Unlock full access