Kotlin — Null Safety
Nullable types
fun main() {
var name: String = "Alice" // Non-null
// name = null // Error!
var nickname: String? = "Ali" // Nullable
nickname = null // OK
}
Safe call operator
fun main() {
val name: String? = "Alice"
println(name?.length) // 5
val nullName: String? = null
println(nullName?.length) // null (not an exception)
}
Elvis operator
fun main() {
val name: String? = null
val length = name?.length ?: 0
println(length) // 0
val display = name ?: "Unknown"
println(display) // Unknown
}
Non-null assertion
fun main() {
val name: String? = "Alice"
println(name!!.length) // 5 (throws if null)
}
Safe casts
fun main() {
val obj: Any = "hello"
val str: String? = obj as? String
println(str?.length) // 5
val num: Int? = obj as? Int
println(num) // null
}
Let with nullable
fun main() {
val name: String? = "Alice"
name?.let {
println("Name is ${it.uppercase()}")
println("Length is ${it.length}")
}
}
Checklists
fun main() {
val name: String? = null
// Check if null
if (name != null) {
println(name.length) // Smart cast
}
// Check and use default
val display = if (name != null) name else "Unknown"
}
Best practices
- Prefer
valovervarfor nullable types - Use safe calls
?.instead of!! - Use Elvis operator
?:for defaults - Use
letfor null-safe operations - Avoid
!!unless absolutely necessary
Mini Practice
Write Kotlin code that:
- Uses safe call operator on a nullable string
- Uses Elvis operator for a default value
- Uses
letwith a nullable variable - Demonstrates safe cast with
as?
Up Next
In the next lesson, you'll learn about Lambdas — functional programming in Kotlin.
Related Topics
Frequently Asked Questions about Null Safety
What is Null Safety in Kotlin?
Null Safety is a fundamental concept in Kotlin. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Null Safety?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Null Safety.
Why is Null Safety important in Kotlin?
Null Safety is essential for Kotlin development. Understanding this concept will help you write better code and solve real-world problems more effectively.