Update:
Kotlin 1.1 has a method called takeIf:
@kotlin.internal.InlineOnly
@SinceKotlin("1.1")
public inline fun <T> T.takeIf(predicate: (T) -> Boolean): T? = if (predicate(this)) this else null
You can use it as follows:
repository.findByUID(request.userId)?.takeIf { someCondition }?.let { service -> }
Kotlin does not contain such a method in stdlib.
However, you can define it:
inline fun <K : Any> K.ifPresent(condition: K.() -> Boolean): K? = if (condition()) this else null
Using this method, your example can be rewritten as:
fun handle(request: Request) {
repository.findByUID(request.userId)?.ifPresent { someCondition }?.let {
service.run(...)
}
}
( ):
listOf(repository.findByUID(userId)).filter { someCondition }.forEach { service.run(...) }