Kotlin

takeIf / takeUnless — Conditional Pipelines

admin by @admin ADMIN
4h ago
Jun 1, 2026
Public
0 0 up · 0 down Sign in to vote
`takeIf { predicate }` returns `this` if the predicate holds, else null. `takeUnless` is the inverse. Combine with `?.let { ... }` for clean conditional transformations.
Kotlin
Raw
fun main() {
    val name = "Alice"

    // Returns name only if not blank, else null
    val greeting = name.takeIf { it.isNotBlank() }?.let { "Hello $it" } ?: "Hello stranger"
    println(greeting)                            // Hello Alice

    // Validate-and-default style
    val port = System.getenv("PORT")
        ?.toIntOrNull()
        ?.takeIf { it in 1..65535 }
        ?: 8080                                  // fallback if missing / invalid / out-of-range
    println(port)

    // takeUnless — the inverse
    val safeQuery = "  ".takeUnless { it.isBlank() } ?: "*"
    println(safeQuery)                           // *

    // In a pipeline — drop a stage cleanly
    val result = listOf(1, 2, 3, 4, 5)
        .filter { it > 0 }
        .takeIf { it.isNotEmpty() }
        ?.average() ?: 0.0
    println(result)                              // 3.0
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.