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 null
1fun parsePositive(s: String): Int? {
// toIntOrNull() gives null for non-numbers; takeIf keeps the value only if it is > 0
2 return s.toIntOrNull()?.takeIf { it > 0 }
3}
4
// Returns the name unless it is empty or only whitespace
5fun getValidName(name: String): String? {
// takeUnless returns null when the condition is true
6 return name.takeUnless { it.isBlank() }
7}
8
// Valid positive number: prints 42
9println(parsePositive("42"))
// -5 is not > 0: prints null
10println(parsePositive("-5"))
// Not a number, so toIntOrNull() returns null: prints null
11println(parsePositive("abc"))
// Print Alice
12println(getValidName("Alice"))
// Only spaces is blank: prints null
13println(getValidName(" "))

Output

42
null
null
Alice
null
Practice typing this code

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

More Kotlin examples at level 5

← Kotlin typing practice