← All languages
Kotlin function of the day
Random

ifBlank

Return a default value if a string is blank.

Description

The ifBlank function returns the result of calling the given lambda if the string is blank (empty or contains only whitespace), or the string itself if it is not blank.

This is useful for providing fallback values for user input or configuration strings. The lambda is only called when the receiver is blank.

ifBlank is available on CharSequence and String types.

Arguments

NameDescriptionOptional
defaultValue A lambda that produces the fallback value when the string is blank. No

Example

val input = "   "
println(input.ifBlank { "default" })  // default

val valid = "hello"
println(valid.ifBlank { "default" })  // hello

Reference