Nullable Types
In this page:
Nullable vs Non-Nullable Types
Appending a ? to a type, such as String?, marks it as nullable, meaning a variable of that type may hold either a real value or null. A plain String (without ?) can never be null.
Example: Nullable vs Non-Nullable Types
fun main() {
var name: String = "Kotlin"
var nickname: String? = null
println("Name: $name, Nickname: $nickname")
}
Login to try C/C++/Java/PHP code in the editor
The Compiler Prevents Null Pointer Exceptions
Because the type system tracks nullability, the compiler refuses to compile code that could crash by calling a method on a null value, forcing you to handle that possibility explicitly.
Example: The Compiler Prevents Null Pointer Exceptions
fun printLength(text: String?) {
if (text != null) {
println("Length: ${text.length}")
} else {
println("Text is null")
}
}
fun main() {
printLength("Kotlin")
printLength(null)
}
Login to try C/C++/Java/PHP code in the editor
Smart Casting a Nullable Value
After a null check like if (text != null), Kotlin smart-casts text to its non-nullable type inside that block, so it can be used just like a normal String without any extra unwrapping.
Example: Smart Casting a Nullable Value
fun shout(text: String?) {
if (text != null) {
println(text.toUpperCase())
}
}
fun main() {
shout("hello")
shout(null)
}
Login to try C/C++/Java/PHP code in the editor
Function Parameters as Nullable
Marking a function parameter as nullable communicates clearly to callers that passing null is an expected, valid case that the function itself will handle.
Example: Function Parameters as Nullable
fun describeAge(age: Int?): String {
return if (age == null) "Age unknown" else "Age is $age"
}
fun main() {
println(describeAge(30))
println(describeAge(null))
}
Login to try C/C++/Java/PHP code in the editor
- Forgetting the
?after a type when a value can legitimately be absent, causing the compiler to disallow assigningnullto it. - Treating a nullable type like a regular one and calling a method directly, which the compiler rejects until the null case is handled.
- Overusing nullable types everywhere out of caution, when many values could be designed to never be null in the first place.
- A type followed by
?, such asString?, can hold either a value of that type ornull. - A non-nullable type, like plain
String, can never holdnull; the compiler enforces this at compile time. - Calling a member directly on a nullable type without handling the null case is a compile-time error.
- Kotlin's null safety catches many null pointer exceptions before the program ever runs.
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: