Nullable types
- Kotlin course
- Beginner
- Lesson 77/116
- 5 min
Learn String? and nullable types.
Nullable types: String?
In Kotlin a type does not accept null by default. val name: String = null is a compile error. For a variable to be null, the type gets a ? suffix: String?.
val name: String? = null // ok
val city: String = null // compile errorThe ? mark tells the compiler the type is nullable; null-risk is tracked at compile time. This prevents most runtime NullPointerException crashes.
Why use nullable variables?
Sometimes a value is genuinely absent: a field not yet fetched from the database, an input the user left blank, or a lookup with no target. null states this "no value" case explicitly.
val nickname: String? = null
val realName: String? = "Ava"A nullable type tells the programmer to manage the null-risk consciously. The ?., !! and ?: operators you will see in the next lessons are the tools for this management.
Practice Print a nullable name set to null
Define a val name: String? = null and print it with println(name).
Starter code
fun main() {
// Define name as String? set to null and print it
}Sample solution
fun main() {
val name: String? = null
println(name)
}Expected output
null
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What happens with val name: String = null?
- It is a compile error Correct answer
- name becomes null
- A runtime exception is thrown
- It returns Unit
Explanation: String (no ? suffix) cannot hold null; it is a compile error.
2 Fill in the blank: nullable type
val name: ____ = null
val name: String? = null
Explanation: String? is the type that can hold null.
3 Match expression to meaning
| Term | Meaning |
|---|---|
String |
cannot be null |
String? |
can be null |
? |
Nullable mark |
null |
No value |