1. Introduction
When you are just starting to write code, if feels like a universal screwdriver: you can use it to check, assign, print, and even “educate” the user with a message like “please type it properly”. And that is true. But over time (sometimes after just two source files) a new problem appears: very often you do not need to “branch”, you need to “filter a value”.
Imagine a typical situation from our console app (we keep evolving a CLI app with commands like add, list, remove, etc.). The user enters a string, and we want to:
- take it if it is OK (not empty, not just spaces, not -1, not "abc" instead of a number),
- otherwise get null so we can handle it nicely using the familiar null-safety and Elvis ?:.
This is where takeIf and takeUnless act like small “filters” for a value.
2. What takeIf is: “keep the value if it passes the check”
takeIf is an extension function that is called on the value itself and returns:
- the same value if the condition is true,
- null if the condition is false.
So the logic reads roughly like this: “take this if…”.
You can remember the signature not as scary math, but as meaning:
value.takeIf { conditionOnValue } // returns value or null
Key effect: the result becomes nullable (T?), which means we can then apply:
- safe call ?.
- Elvis ?:
- a regular check with if (x != null)
In Kotlin documentation and examples you will often see the style .takeIf { it >= 0 } ?: ... as a compact way to “take the value only if it is valid”.
A mini table for your brain
| Tool | Idea | Returns |
|---|---|---|
|
“Keep the value if cond = true” | |
|
“Keep the value if cond = false” | |
|
“If the left side is null, take the right side” | non-null result (usually) |
3. Elvis ?: in this pairing: “if it does not fit—use a fallback”
You met the Elvis operator in the null-safety topic: an expression like
val x = nullableValue ?: defaultValue
means: if the left side is null, take defaultValue.
Why does takeIf almost always go well with ?:? Because takeIf is specifically about producing null as a “validity marker”, and ?: turns that marker into clear behavior: a default value, an error message, an early return from a function, or something else.
4. Example: validating the result of indexOf
Now a real-life string scenario: indexOf(...) returns -1 if it did not find anything. This is not an exception and not a JVM error; it is simply “by convention”. But you cannot use -1 as an index for substring.
Usually people write:
val at = email.indexOf('@')
if (at >= 0) { ... } else { ... }
But you can also do it like this—via takeIf + Elvis:
fun main() {
val email = "aliceexample.com"
val at = email.indexOf('@')
val safeAt = at.takeIf { it >= 0 } ?: -1
println(safeAt) // -1
}
OK, this is not super useful yet: we just returned -1. More useful is to use a fallback that is guaranteed to be safe.
For example, sometimes it is convenient to say: “if there is no "@", assume there is no domain”:
fun main() {
val email = "aliceexample.com"
val at = email.indexOf('@')
val domain = at.takeIf { it >= 0 }
?.let { email.substring(it + 1) } // (we will cover let later; today, without it)
?: "INVALID"
println(domain) // INVALID
}
But wait. We have not covered scope functions in this day yet (that will be later), so let us do the same thing without let, honestly and clearly:
fun main() {
val email = "aliceexample.com"
val at = email.indexOf('@')
val domain = if (at.takeIf { it >= 0 } != null) {
email.substring(at + 1)
} else {
"INVALID"
}
println(domain) // INVALID
}
Here you can see an important idea: takeIf is not a “replacement for if forever”; it is a tool that allows you to turn a “bad value” into null.
In official Kotlin examples you can find a similar trick: they search for an index, then do .takeIf { it >= 0 } ?: s.length to get a safe boundary.
5. Example: “an empty string after trim” is also invalid input
The user typed " " (three spaces). Formally it is a non-empty string (length = 3), but its meaning is like the promise “I will start studying on Monday”—i.e., zero.
A common pattern: first trim(), then a check.
takeIf lets you write this very linearly:
fun main() {
val raw = " "
val name = raw.trim().takeIf { it.isNotEmpty() } ?: "UNKNOWN"
println(name) // UNKNOWN
}
This reads almost like a sentence: “take the trimmed string if it is not empty, otherwise UNKNOWN”.
6. takeUnless: “the same, but the other way around”
takeUnless is the mirror sibling of takeIf.
- takeIf { cond } keeps the value when cond == true
- takeUnless { cond } keeps the value when cond == false
Why do we need it if we can write takeIf { !cond }? Because sometimes the inversion reads simpler exactly as “if NOT…”.
Imagine that in our CLI commands we forbid some “reserved words” for a category, for example "all" (because the command list all can mean “show everything”).
fun main() {
val rawCategory = "all"
val category = rawCategory.trim()
.takeUnless { it.lowercase() == "all" }
?: "uncategorized"
println(category) // uncategorized
}
This reads fine: “take the category if it is NOT all, otherwise uncategorized”.
7. How this helps in a CLI: neat argument parsing
Now an important practical point. In commands like:
- add food 120 coffee
- remove 3
- list food
user input is always “dirty”: extra spaces, empty arguments, weird numbers, sometimes an empty line.
We already know how to normalize spaces via Regex("""\s+""").replace(...) (this was in the previous lecture). Now we will add guard conditions via takeIf/takeUnless, so that each intermediate value either becomes normal or turns into null.
Normalize a token: “string or null”
Let us make a small helper function. It will be useful almost everywhere: category name, note text, command.
fun normalizeToken(raw: String): String? {
val cleaned = raw.trim()
return cleaned.takeIf { it.isNotEmpty() }
}
And test it:
fun main() {
println(normalizeToken(" milk ")) // milk
println(normalizeToken(" ")) // null
}
Returning null here is not “bad”; it is a useful signal: next you can use ?: and decide what to do.
Parse a positive amount: “number or null”
In an expense tracker, the amount must be a number, and most often positive. With takeIf, you can do this without extra branching:
fun parsePositiveIntOrNull(raw: String): Int? {
val n = raw.trim().toIntOrNull()
return n?.takeIf { it > 0 }
}
Test it:
fun main() {
println(parsePositiveIntOrNull(" 120 ")) // 120
println(parsePositiveIntOrNull("-5")) // null
println(parsePositiveIntOrNull("abc")) // null
}
Two ideas work together here: toIntOrNull() yields null for non-numeric input, and takeIf { it > 0 } turns “a number, but an invalid one” into null as well. As a result we get a single “did not pass validation” signal.
takeIf + Elvis as a one-line guard
Sometimes you want, within a single expression, to get either a correct value or a fallback.
For example: the user types remove id. If id is invalid, we use 0 as a marker (or we could print an error, but today we focus on the expression).
fun main() {
val rawId = " -10 "
val id = rawId.trim().toIntOrNull()?.takeIf { it >= 1 } ?: 0
println(id) // 0
}
This is very similar to the classic idiom from the documentation: “take the value if it is valid, otherwise substitute a length/boundary/default”.
8. Mini example: parsing remove via guard expressions
Let us build a small piece of logic for the remove command. We are not writing the entire project in this lecture, but we will keep moving the same style forward.
Scenario: the user enters a line. We want to get id: Int?, where null means “it did not work”.
fun parseRemoveIdOrNull(line: String): Int? {
val parts = Regex("""\s+""").replace(line.trim(), " ").split(" ")
if (parts.isEmpty()) return null
if (parts[0].lowercase() != "remove") return null
val rawId = parts.getOrNull(1) ?: return null
return rawId.toIntOrNull()?.takeIf { it >= 1 }
}
Yes, there is an if here. That is fine. We use takeIf not as a religion, but as a convenient “mini filter” at a specific step.
You can test it:
fun main() {
println(parseRemoveIdOrNull("remove 3")) // 3
println(parseRemoveIdOrNull("remove -2")) // null
println(parseRemoveIdOrNull("remove abc")) // null
}
It is useful to notice: takeIf helps exactly where we “already have a value, but need to validate it with a condition”.
9. How to think about takeIf/takeUnless and where they fit
Mindset: “turn bad into null → handle it in one uniform way”
Once you master this style, code often starts to look like a validation pipeline. Even without scope functions (we do not touch them today), you can keep a simple flowchart in mind:
flowchart TD
A[Raw value] --> B[Normalization: trim/replace]
B --> C{Condition check}
C -->|OK| D[Value]
C -->|FAIL| E[null]
E --> F[Elvis ?: fallback/message/exit]
Meaning: takeIf/takeUnless is a convenient implementation of the node “check condition → null on failure”.
When takeIf/takeUnless improve readability, and when they get in the way
Here it is important not to fall into a typical beginner trap: “oh, a new feature—now I will apply it to the whole project”. That is how PRs appear after which colleagues start drinking chamomile tea instead of coffee.
takeIf/takeUnless are usually appropriate when the condition is short and directly describes validity. Classic examples: it >= 0, it.isNotEmpty(), it in 1..10. In Kotlin examples you can see a style where a string is turned into a value and then immediately filtered by length via takeIf—that is a good, simple predicate.
When the condition is long, with several checks and “and also this, and also that”, a plain if often reads better, because you can break the thought into multiple lines and give variables meaningful names.
A set of mini examples (5–10 lines)
Sometimes it is better to see a few short situations once than to hear a definition a hundred times.
Take a string only if it “looks like a command”
fun main() {
val raw = " add food 120 coffee "
val commandLine = raw.trim().takeIf { it.contains(' ') } ?: ""
println(commandLine) // add food 120 coffee
}
Discard a too-short token
fun main() {
val token = "ok"
val good = token.takeIf { it.length >= 3 } ?: "too_short"
println(good) // too_short
}
takeUnless as “ban a value”
fun main() {
val category = "root"
val safe = category.takeUnless { it == "root" } ?: "guest"
println(safe) // guest
}
10. Typical mistakes when using takeIf/takeUnless
Mistake No. 1: forgetting the result is nullable and using it like a regular value.
takeIf and takeUnless almost always return T?, even if the original value was T. A beginner writes val x = s.takeIf { ... } and immediately does x.length. The compiler complains fairly, but the student does not. The fix is simple: either add Elvis ?:, or check for null, or keep chaining via safe call ?..
Mistake No. 2: trying to replace an entire “business-logic branch” with takeIf.
If, on invalid input, you need to print a message, ask the user to retry, log an error, or do different actions, that is no longer “filtering a value”; it is branching behavior. In such places if/when is usually more honest and readable: you are not hiding important logic in one line “for prettiness”.
Mistake No. 3: overusing takeUnless when it is easier for the reader to see takeIf.
takeUnless { it == "all" } may look fine, but takeUnless { it.length < 3 } already forces the brain to do a double negation. If the phrase “take if …” sounds more natural, use takeIf. If “take if NOT …” is more natural, use takeUnless.
Mistake No. 4: writing conditions that are too complex directly inside takeIf { ... }.
When the predicate grows into “three conditions, two &&, one ||, plus parentheses”, the code stops being teachable. In that case, it is better to move the check into a separate function with a descriptive name (e.g., isValidCategoryName(s)), or at least introduce intermediate vals and only then apply takeIf.
Mistake No. 5: confusing an “invalidity marker” with the “real meaning of null”.
In this topic, null is a convenient technical signal “did not pass validation”. But later in the course you will design types so that null does not mean “anything and everything”. So try to make null in your code either an explicitly expected result (parse...OrNull) or a conscious “flag” produced by takeIf/takeUnless that is handled immediately via ?: or a check.
GO TO FULL VERSION