1. Why Kotlin needs @Nullable/@NotNull
Kotlin on the JVM constantly interacts with the Java world: the JDK, any Java libraries, legacy code in your project. In Kotlin, this looks “Kotlin-ish”, but there is a fundamental difference: in Java, historically null is a normal value, and it is far from always clear from a signature whether a method may return null.
This leads to the core topic: how Kotlin learns the nullability of Java methods and collections—when it sees a clear contract (String or String?), and when it leaves platform ambiguity (String!).
When you write Kotlin code, null-safety can feel like “compiler magic”: you write String, and everything is safe. But as soon as you call Java code, reality shows up: in Java, null is allowed almost everywhere, and the answer to “can this method return null?” is often only in the library author’s head (and sometimes only in an issue tracker).
For Kotlin to be strict not only inside Kotlin code but also when calling Java code, it needs hints. Those hints are Java nullability annotations: @Nullable (“may be null”) and @NotNull (“null is forbidden”). Kotlin can recognize such annotations (in particular, JetBrains annotations) and build Kotlin-visible types based on them. This is described as enhancing signatures—refining type signatures when importing Java APIs into Kotlin.
It is important to understand a subtle point: annotations in Java are not an “ironclad guarantee”; they are a contract. That is, the author promises: “I return non-null.” Kotlin trusts the contract enough that it lets you write stricter code, but if the contract is violated, the JVM can still “carry through” null—and then you’ll get a crash (at least earlier and more clearly than somewhere later in the chain).
2. How Kotlin builds types: T, T?, and T!
The short formula is: Kotlin tries to turn “unknown stuff from Java” into a “clear Kotlin type”. It prioritizes information: first it looks at annotations (@Nullable/@NotNull), and if there are none (or they conflict), it may leave a platform type (T!).
In the Kotlin specification, this is stated roughly as follows: a Java type without annotations becomes a flexible type (the IDE often shows it as T!), and the presence of annotations can “narrow” this type toward T or T?.
Let’s fix a simple table that is convenient to keep in mind:
| How it looks in Java | How Kotlin usually sees it |
|---|---|
| Foo (no annotations) | |
| @Nullable Foo | |
| @NotNull Foo | |
Now the key practical part: why Foo! is not “yet another kind of nullable”, but rather “dangerous uncertainty”.
- Foo? forces you to write safe code.
- Foo forces you to live like an optimist (and sometimes crash if that optimism was misplaced).
- Foo! is the state where “the compiler isn’t sure”, and sometimes it allows you to write code as if it were Foo, even though null may arrive at runtime.
Here is a small example showing the compiler’s “psychology”: if you explicitly choose the type String, Kotlin is allowed to insert a runtime check and “fail fast”, because you declared a strict contract (in the specification this is described as generating checks when an expected type exists).
fun main() {
val rawFromJava = System.getProperty("my.app.mode") // may be null
val mode: String = rawFromJava // may crash immediately here if rawFromJava == null
println(mode.length)
}
In a correct program, we would of course “land” this as String?, but the fact itself matters: as soon as you choose T in Kotlin, it’s as if you sign a paper saying “I am sure this is not null”.
3. Where to place @Nullable/@NotNull in Java
So far we spoke abstractly: “a Java method is annotated”. But beginners often get stuck at the level of “where exactly do I put the annotation, and what exactly does it mean?”. Plus, there is another layer of complexity: an annotation may apply not only to the type itself but also to type arguments (for example, list elements).
The Kotlin specification lists what can be annotated: a field (annotation applies to the field type), a method (annotation applies to the return type), a parameter (annotation applies to the parameter type), and it separately mentions type-use annotations (Java 8+)—that is TYPE_USE.
Imagine that somewhere in a Java library there is an interface like this (we don’t write or compile it—just read it as an API “passport”):
interface UserDirectory {
@NotNull String findDisplayName(@NotNull String id);
@Nullable String findEmail(@NotNull String id);
}
In Kotlin, this will read very naturally:
fun printUserInfo(dir: Any /* suppose this is UserDirectory */) {
// roughly: displayName: String (non-nullable)
// roughly: email: String? (nullable)
}
But the most interesting part starts when Java annotates the inside of collections. For example:
interface TagService {
@NotNull List<@Nullable String> loadTags();
}
Then Kotlin sees: “the list definitely exists, but elements may be null”—that is, roughly List<String?>.
And this is not a theoretical rarity. In Kotlin compiler 2.x documentation, an example is given where with a Java signature like @NotNull ResultContainer<@Nullable String> fetchData() Kotlin carries nullability into the type argument and gets ResultContainer<String?>.
4. Collections: null in the container vs null in the elements
When it comes to lists and sets, people often think that a “nullable collection” is a single problem. In practice there are two: the collection itself (the container) may be null, and there may be null values inside (elements). These cases break code in different ways, and Kotlin makes you spell out both.
The contrast is easiest to see in types:
- List<String>? means “the list may be absent, but if it exists—strings inside are not null”.
- List<String?> means “the list exists, but it may contain nulls”.
- List<String?>? means “the list may be missing, and if it exists—it may contain nulls”.
If you see such a type (or suspect you have a platform type that behaves this way), the most mature approach is boundary normalization: turn the “dirty external world” into the “clean internal world of your application”.
For normalization, you have familiar tools: ?: emptyList(), filterNotNull(), mapNotNull(). We aren’t learning anything “new and scary”—we’re just applying basic Kotlin correctly.
Here is a small and very practical gateway function:
fun normalizeTags(raw: List<String?>?): List<String> {
return raw
?.map { it?.trim() } // prepare elements (trim)
?.filterNotNull() // drop null elements
?.filter { it.isNotEmpty() } // drop empty after trim
?: emptyList() // if there is no list, treat it as empty
}
And an example of usage:
fun main() {
val raw: List<String?>? = listOf(" kotlin ", null, " ", "jvm")
val tags = normalizeTags(raw)
println(tags) // [kotlin, jvm]
}
Note the style: we do not try to “carry nullable further through the whole program”. We accept reality once at the boundary (data is dirty), clean it, and then work with a normal List<String>.
And this is where Java annotations @Nullable/@NotNull truly help: if the library honestly declares @NotNull List<@Nullable String>, Kotlin will show you the truth as List<String?>, and you immediately understand that you need filterNotNull().
5. Integrating into a CLI: “dirty input” → “clean Kotlin model”
In this course we already have a practical console app: it stores data in collections, accepts commands, and tries to be resilient to messy input. Now we’ll add a small but typical layer: “data came from outside” (in reality it could be a Java library, a plugin, or an SDK), and we want to integrate this data into domain code without spreading null across the whole project.
Imagine that from “outside” we receive category names. We won’t write Java code, but we will write Kotlin as if we were given a function that returns “a list of strings, possibly with nulls”. Even if in Java it was annotated, we still want a single gateway.
Let’s build a utility that turns an external list into a list of category names suitable for add/list commands:
private fun normalizeCategoryNames(raw: List<String?>?): List<String> {
return raw
?.map { it?.trim()?.lowercase() }
?.filterNotNull()
?.filter { it.isNotEmpty() }
?: emptyList()
}
Now we’ll add usage in our “main loop” (or in a command handler). Let the categories command print available categories (in reality—from an external source):
fun main() {
// as if it came from a Java library:
val rawFromJava: List<String?>? = listOf(" Food ", null, "Transport", " ")
val categories = normalizeCategoryNames(rawFromJava)
println("Categories (${categories.size}):")
println(categories.joinToString()) // food, transport
}
What matters methodologically: we don’t discuss why there is null, and we don’t try to fix the whole world. We just build a “sanitizing gateway”: further in the app, categories are a normal List<String>, and command code does not turn into an endless festival of ?.
If tomorrow the external source becomes more honest and starts returning @NotNull List<@NotNull String>, then the Kotlin type will become even stricter, but our gateway will still remain correct (it will just be slightly redundant).
6. Why Kotlin keeps T!
It helps to take off the rose-colored glasses: “annotations will save the world” sounds nice, but reality is more complex. Kotlin tries to use @Nullable/@NotNull, but it has an important compatibility rule: if annotations disappear (or the library has none), the code should still have a chance to compile. Therefore, when things are ambiguous, Kotlin may “fall back” to a platform type and possibly show a warning.
The specification describes this directly: if an “enhanced” signature is not compatible (for example, it conflicts with signatures in a type hierarchy), then enhancing can be dropped, and instead of a strict type Kotlin will use a platform type.
We need one practical takeaway from this:
If you see that a Java method returns Something!, don’t try to “force the compiler by willpower”. Do what we did before: at the boundary choose Something? and normalize data. This works both when annotations don’t exist and when they do, but Kotlin did not apply them for some reason.
For example, this coding style is robust:
fun safeToken(raw: String?): String? {
return raw
?.trim()
?.takeIf { it.isNotEmpty() }
}
fun main() {
val tokenFromJava: String? = System.getenv("APP_TOKEN") // came from outside
val token = safeToken(tokenFromJava)
println(token ?: "<no token>") // <no token>
}
How to see String, String?, and String! in IntelliJ IDEA
The IDE is your X-ray: it helps you understand what Java code actually returned and what Kotlin managed to infer from annotations. So it’s useful to build a habit of occasionally stopping and looking at the expression type.
In IntelliJ IDEA, it’s usually enough to hover your cursor over an expression or a variable.
- If you see String, it means some contract guarantees non-null.
- If you see String?, it means someone honestly said “may be null” (and you must handle it).
- And String! is the sign “Caution: surprises possible”: Kotlin is not sure, and the responsibility is on you again.
One more hint: compiler messages about nullability are usually quite literal. If you try to pass String? where String is expected, it will say Type mismatch. If you try to call .length on String?, it will remind you about a safe call. It’s not “scolding”—it’s simply your program at the stage of “I won’t let myself step on a rake”.
7. Typical mistakes when working with @Nullable/@NotNull and Java collections
Mistake №1: believing that @NotNull is a magic spell that physically prevents null.
An annotation is a contract, not armor. Kotlin may trust the contract and give you the type T, but the JVM can still deliver null if the library is wrong. So even with @NotNull, it is important to understand where you trust the external world and where you want to “fail fast” and diagnose the problem.
Mistake №2: confusing “the list may be null” with “the list may contain nulls”.
List<String>? and List<String?> break code differently. In the first case, you can’t even iterate without checking the container; in the second, you can iterate, but you must decide the fate of each element. With Java integrations, it’s easy to get both risks at once, and then you need a careful sanitizing gateway: ?: emptyList() plus filterNotNull().
Mistake №3: letting platform types (T!) leak deep into domain logic.
If you allow String! or MutableList<String!>! to roam around your project, a “sudden NPE” becomes only a matter of time. It is much cheaper to decide once at the boundary: “is this nullable or not?”, and then work with normal Kotlin rules.
Mistake №4: “fixing” everything with !! because it’s faster.
!! is not an integration tool; it’s an emergency button “crash the program here”. Sometimes that is indeed the right decision (for example, the app cannot run without the value), but when handling external data you more often need a fallback (?:), normalization (trim(), takeIf()), and soft behavior (an empty list instead of a null list).
Mistake №5: expecting List in Kotlin to make data immutable if the source is Java.
Even if you hold a reference as List<String>, the Java source may have returned a mutable collection. If your scenario requires a stable snapshot, make a copy with toList() after normalization. This is not “paranoia”; it’s a way to make behavior predictable, especially when data comes from someone else’s code.
GO TO FULL VERSION