July 2018
Intermediate to advanced
400 pages
12h 14m
English
The last stop on our tour of the standard functions is takeIf. takeIf works a bit differently than the other standard functions: It evaluates a condition provided in a lambda, called a predicate, that returns either true or false depending on the conditions defined. 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 is readable and writable.
val fileContents = File("myfile.txt")
.takeIf { it.canRead() && it.canWrite() }
?.readText()
Without takeIf, this would be more verbose:
val file = File("myfile.txt") val fileContents = if (file.canRead() && file.canWrite()) { file.readText() ...Read now
Unlock full access