Explain it simply
Explain it simply
A String is a guarantee: there really is text in this box. The text may be empty (""), but it is never missing (null). A String? is a box labelled "there may be text, or there may be nothing". Because the ? is right there in the type, both you and the compiler know the box must be checked before you use what is inside.
That split means "the program crashed because something was null" is caught while you compile, not after the program ships. In many languages the same mistake is only discovered when a real user hits it.
Problem → Why → Solution
The problem: the crash nobody saw coming
On a profile screen the nickname field is optional. A developer writes nickname.length to get its size. In many languages that compiles, and every tester who filled in a nickname sees nothing wrong. Then a user who skipped the field opens the app and it crashes. In the Java world this is the NullPointerException, one of the most common causes of crashes.
In Kotlin, the code below does not even compile, so the same bug shows up as a red underline in the developer's editor long before it reaches a user.
fun nicknameLength(nickname: String?): Int {
// error: only safe (?.) or non-null asserted (!!.) calls are allowed
// on a nullable receiver of type 'String?'.
return nickname.length
}Why can Kotlin stop this?
Kotlin records "could this value be missing?" as part of the type. Declaring nickname as String? tells the compiler it may be null, so it refuses to let you treat it as a plain String until you have dealt with null. Putting that knowledge into the type moves the check from run time to compile time.
Core concept: the type says whether null is possible
In Kotlin every type is non-null by default. Writing val name: String = null makes kotlinc answer: null cannot be a value of a non-null type 'String'. To allow null, add ? after the type; String? is a separate type from String. You can put a String into a String? (it is the wider type), but not the other way round without a null check, which gives: initializer type mismatch: expected 'String', actual 'String?'.
You cannot call a member on a nullable value directly. nickname.length fails with: only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of type 'String?'. The simplest way to deal with it is an if (nickname != null) check. Inside the checked part the compiler remembers that null is impossible and lets you use nickname as a String; that is called a smart cast.
A smart cast only works when the compiler can be sure the value cannot change between the check and the use. It works on a local val, and on a local var that is not modified in between. It does not work on a var property of a class, because other code, or another thread, could change it in the gap. In that case copy the property into a local val and check that.
The !! operator (not-null assertion) tells the compiler "I promise this is not null". If you are wrong, the JVM throws a NullPointerException. In other words, !! switches off the protection and moves the problem back to run time. Do not use it where null is a normal, expected situation.
| Question | String | String? |
|---|---|---|
| Can it hold null? | No | Yes |
| Call x.length directly? | Yes | No, compile error |
| Assign to the other type? | Into String?: yes | Into String: only after a null check |
- Type says whether null is possible
- Compiler blocks unsafe member calls
- A null check proves it is safe
- !! skips the proof and risks a crash
Treat a nullable as a box you may not open yet; only a null check hands you the key.
General pattern
val sure: Type = value // never null
var maybe: Type? = valueOrNull // may be null
if (maybe != null) {
// inside this block, maybe is smart-cast to Type
}
val forced = maybe!! // throws NullPointerException if nullA type with ? accepts null. Inside the block guarded by maybe != null you may use maybe as a Type. The last line uses !!, which crashes on null and is the form to avoid.
Example: non-null, nullable and a null check
This program puts String and String? side by side and shows how to handle null safely. toIntOrNull() returns null instead of crashing for text such as "4x", so its result has to be held in an Int?. Predict the output before you run it.
fun main() {
val username: String = "thutatech"
// val broken: String = null // compile error: null is not a String
var nickname: String? = "Sai"
println("$username / $nickname")
nickname = null
println("$username / $nickname")
val qty: Int? = "4x".toIntOrNull()
if (qty != null) {
println("Quantity plus one: ${qty + 1}")
} else {
println("Not a number")
}
}Code breakdown
- Non-null type
val username: String = "thutatech"String is non-null, so this variable can never hold null. If you uncomment the line val broken: String = null in the code, it will not compile.
- Nullable type
var nickname: String? = "Sai"Because of the ?, nickname can hold a String or null. For now it holds "Sai".
- Assigning null
nickname = nullnickname is a String?, so this assignment is accepted; username could not take it. Printing it afterwards produces the text "null".
- A source of null
val qty: Int? = "4x".toIntOrNull()"4x" cannot be converted to an Int, so toIntOrNull() returns null. That is why the result variable is declared Int?.
- Null check and smart cast
if (qty != null) {Inside this checked block qty counts as an Int, so qty + 1 is allowed. In this run qty is null, so the else branch executes and prints "Not a number".
thutatech / Sai
thutatech / null
Not a number- An Int? value arrives
- Compare it with null
- Non-null path: smart cast to Int
- Null path: handle the missing value
Not null
Use it as a plain Int
Null
Show a message or fall back to a default
Where smart casts work and where they stop
class Profile(var bio: String?) is a tiny class with one changeable property (classes get their own lesson later). The obvious version, if (profile.bio != null) { return profile.bio.length }, does not compile, because the compiler cannot promise that bio is unchanged after the check. The code below avoids the problem by copying the property into a local val first. Nobody can reassign a local val behind your back, so the smart cast is allowed.
class Profile(var bio: String?)
fun bioLength(profile: Profile): Int {
val bio = profile.bio
return if (bio != null) bio.length else 0
}
fun main() {
println(bioLength(Profile("abc")))
println(bioLength(Profile(null)))
}The error from the first version
Checking the property directly and then using it makes kotlinc 2.1.21 report: smart cast to 'String' is impossible, because 'bio' is a mutable property that could be mutated concurrently. The message already hints at the fix: move the value somewhere that cannot change, a local val.
!! and its safer replacements
There are only a few good uses of !!, for instance when you have already proved a value is not null in a way the compiler cannot see. In most other cases requireNotNull(value) { "message" } is better: if the value is null it throws an IllegalArgumentException with your own message, so the log says exactly what went wrong. checkNotNull works the same way but throws an IllegalStateException.
fun main() {
val port: Int? = "abc".toIntOrNull()
try {
println(port!! + 1)
} catch (e: NullPointerException) {
println("!! threw ${e::class.simpleName}")
}
try {
val checked = requireNotNull(port) { "port must be a number" }
println(checked + 1)
} catch (e: IllegalArgumentException) {
println("requireNotNull threw: ${e.message}")
}
println("Hello, $port")
}The output is "!! threw NullPointerException", "requireNotNull threw: port must be a number" and "Hello, null". The !! throws with no message (e.message is null), while requireNotNull shows yours. Look at the last line too: putting null into a string template is not an error, it simply prints the text "null", a mistake we meet again in the list below.
In real projects
Where this shows up in real projects
In production code null usually shows up at the border with the outside world: a missing field in a JSON response, a NULL column in a database, an empty form input, an environment variable that may not be set, text that cannot be parsed such as "abc".toIntOrNull(), or an element that is not in a list. A good pattern is to hold such values as ? types at the border and convert them to non-null types before they reach the core of your code.
Calling Java libraries needs care. Java types carry no nullability, so Kotlin treats values coming from Java as "platform types" (written String!), and if one is null the compiler cannot protect you. Declaring such a value as String? on your side is the safe choice. Kotlin code that keeps null at the border and uses non-null types inside sees far fewer NullPointerExceptions than code that lets null travel everywhere.
Common mistakes
Common mistakes
1. Sprinkling !! to silence the compiler
If nickname.length is rejected and you turn it into nickname!!.length, it compiles but crashes for the user whose nickname is null, which recreates the very problem Kotlin was solving. When null is possible, check it with if, supply a default (next lesson), or use requireNotNull with a clear message.
2. Expecting a smart cast on a var property
Following if (profile.bio != null) with profile.bio.length gives the error "smart cast ... is impossible, because 'bio' is a mutable property". The fix is to copy it with val bio = profile.bio and check that local, or to make the property a val.
3. Letting null leak into text
With a null nickname, "Hello, $nickname" is not an error: it shows the user the text "Hello, null". Handle null explicitly, and avoid hiding it behind a stand-in such as "" or -1 that later code may mistake for real data.
4. Making everything nullable "just in case"
If every parameter is a String?, null checks spread into every function. Use ? only when absence is a genuine state of the thing you are modelling; otherwise keep the type non-null.
Best practices
Best practices
- Start with non-null types and add ? only when absence is a real state of what you model.
- Deal with null at the border (parsing, lookups, JSON, databases) so the inside of your code works with non-null types.
- Prefer requireNotNull and checkNotNull with a message over !!, so a failure carries its reason.
Mini challenge
Mini challenge: parsing a port number
Write a function that safely converts the port text read from a config file into an Int. It returns null when the text is missing (null), when it is not a number, or when the number is outside the valid range 1..65535. Then print the result in a human-readable way.
- Write parsePort(text: String?): Int? without using !!
- Return null straight away when text is null
- trim() the text and convert with toIntOrNull(); return null if that fails
- Return null unless the number is between 1 and 65535
- describe(text) prints "port N ok" or "invalid port: <text>"
fun parsePort(text: String?): Int? {
// TODO: null check on text
// TODO: trim, then toIntOrNull(), check the result for null
// TODO: range check 1..65535
// TODO: return the valid number
}
fun describe(text: String?) {
// TODO: call parsePort and print one of the two messages
}
fun main() {
// TODO: describe "8080", " 443 ", null, "http" and "70000"
}Expected: The program should print: port 8080 ok port 443 ok invalid port: null invalid port: http invalid port: 70000
Show hint
After if (text == null) return null you can use text as a String for the rest of the function (a smart cast). Store the result of toIntOrNull() in a local val, check it for null, and only then compare it with the range limits.
Show solution
fun parsePort(text: String?): Int? {
if (text == null) return null
val number = text.trim().toIntOrNull()
if (number == null) return null
if (number < 1 || number > 65535) return null
return number
}
fun describe(text: String?) {
val port = parsePort(text)
if (port != null) {
println("port $port ok")
} else {
println("invalid port: $text")
}
}
fun main() {
describe("8080")
describe(" 443 ")
describe(null)
describe("http")
describe("70000")
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Kotlin types are non-null by default; add ? as in String? to allow null, and note that String? and String are different types.
- You cannot call members directly on a nullable value; after if (x != null) the compiler smart-casts x to non-null in that block.
- Smart casts do not work on var properties of a class; copy the value into a local val and check that.
- !! throws a NullPointerException on null and removes the compile-time protection, so use it rarely; requireNotNull with a message is the better tool.
Kotlin language guide — Kotlin