How to Declare Nullable Types in Kotlin: Simple Guide
In Kotlin, you declare a nullable type by adding a
? after the type name, like String?. This tells the compiler the variable can hold either a value or null.Syntax
To declare a nullable type in Kotlin, add a ? after the type name. This means the variable can hold a value of that type or null.
- TypeName?: The question mark makes the type nullable.
- var or val: Use
varfor mutable orvalfor immutable variables.
kotlin
var name: String? = null val age: Int? = 25
Example
This example shows how to declare nullable variables and safely print their values using Kotlin's safe call operator ?. to avoid errors when the value is null.
kotlin
fun main() {
var nullableName: String? = null
println("Name length: " + nullableName?.length) // prints null safely
nullableName = "Alice"
println("Name length: " + nullableName?.length) // prints length of "Alice"
}Output
Name length: null
Name length: 5
Common Pitfalls
Common mistakes include forgetting to add ? for nullable types or trying to use nullable variables without safe calls or null checks, which causes errors.
Always use safe calls ?., the Elvis operator ?:, or explicit null checks before accessing nullable variables.
kotlin
fun main() {
var name: String? = null
// Wrong: accessing length directly causes error
// println(name.length) // ERROR
// Right: use safe call
println(name?.length) // prints null safely
// Or use Elvis operator to provide default
println(name?.length ?: 0) // prints 0
}Output
null
0
Quick Reference
| Concept | Syntax | Description |
|---|---|---|
| Nullable type declaration | var x: Type? | Variable can hold a value or null |
| Safe call operator | x?.property | Access property only if x is not null |
| Elvis operator | x ?: default | Provide default if x is null |
| Non-null assertion | x!! | Assert x is not null (throws error if null) |
Key Takeaways
Add a question mark (?) after a type to declare it nullable in Kotlin.
Use safe calls (?.) or null checks to access nullable variables safely.
Avoid accessing nullable variables directly without handling null to prevent errors.
The Elvis operator (?:) helps provide default values when null occurs.
Non-null assertion (!!) should be used carefully as it throws an error if the value is null.