// Created on savesnippets.com · https://savesnippets.com/5foZj1kzhFqoqk 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 }