Compose nullable operations deliberately
A safe call ?. runs an operation only for a non-null receiver. Elvis ?: supplies an alternative when the expression to its left is null. let transforms or works with a value named it, or an explicit lambda parameter.
fun parseBudget(input: String?): Int? =
input?.trim()?.toIntOrNull()?.takeIf { it > 0 }
fun main() {
val budget = parseBudget(" 50 ") ?: 25
println(budget)
parseBudget("10")?.let { minutes ->
println("Accepted $minutes minutes")
}
}
Safe calls propagate absence through the pipeline. takeIf adds domain validation after parsing. The fallback of 25 is an intentional policy; if invalid input must be shown to the user, returning a default would hide an error instead.
Elvis applies to the entire nullable expression, not just the initial receiver. A transformation returning null can trigger the fallback even when the input was non-null.
Exercise
Write a function that returns a trimmed nonblank email string or null without attempting full email validation. Test null, whitespace, and a populated value.
Check: explain when a fallback is appropriate and when the caller needs an explicit validation error.