takeIf and takeUnless in Kotlin
Level 5313 keystrokes
takeIf returns the value when the condition is true and null otherwise; takeUnless does the opposite. Combined with toIntOrNull() and ?., they turn validation into a short expression that yields null for invalid input.
Kotlin code
// Returns the number only if the string is a positive integer, otherwise null1fun parsePositive(s: String): Int? { // toIntOrNull() gives null for non-numbers; takeIf keeps the value only if it is > 02 return s.toIntOrNull()?.takeIf { it > 0 }3}4 // Returns the name unless it is empty or only whitespace5fun getValidName(name: String): String? { // takeUnless returns null when the condition is true6 return name.takeUnless { it.isBlank() }7}8 // Valid positive number: prints 429println(parsePositive("42"))// -5 is not > 0: prints null10println(parsePositive("-5"))// Not a number, so toIntOrNull() returns null: prints null11println(parsePositive("abc"))// Print Alice12println(getValidName("Alice"))// Only spaces is blank: prints null13println(getValidName(" "))Output
42 null null Alice null
Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this Kotlin code and how often they appear.
(× 14)× 14"× 10:× 4.× 4{× 4}× 4?× 3-× 1>× 1