October 2021
Intermediate to advanced
500 pages
16h 23m
English
The last stop on our tour of the scope functions is takeIf. takeIf works differently than the other scope functions: It evaluates a predicate condition provided in a lambda that returns either true or false. If the condition evaluates as true, the receiver is returned from takeIf. If the condition is false, null is returned instead.
Consider the following example, which reads a file if and only if it exists.
val fileContents = File("myfile.txt")
.takeIf { it.exists() }
?.readText()
Without takeIf, this would be more verbose:
val file = File("myfile.txt")
val fileContents = if (file.exists()) {
file.readText()
} else {
null
}
The takeIf version does not require the temporary variable file, nor does it need to specify ...
Read now
Unlock full access