I am trying to perform a simple side-effect in Kotlin:
fun handle(request: Request) {
repository.findByUID(request.userId)?.let {
if (someCondition) return
service.run(...)
}
}
As you can see, the side-effect should be performed when the repository returns a non-null value and when someCondition is satisfied.
Is there any Kotlin-way of doing this rather than using if{}-return constructs?
In Java 8, it could be achieved by:
optional
.filter(...)
.ifPresent(...)
Update: Kotlin 1.1 has a method called
takeIf
:You can use it this way:
Kotlin doesn't contain such method in the stdlib.
However, You can define it:
Using this method your example can be rewritten as:
Another option may be to use the built in extensions for list (but there is an overhead of using lists):