Kotlin
Beginner
1 min read
Nullable Types and the Safe-Call Operator
Example
fun findUser(id: Int): String? {
return if (id == 1) "Alice" else null
}
fun main() {
val user: String? = findUser(2) // may be null
// Safe call — returns null if user is null
val length: Int? = user?.length
println("Length: $length") // Length: null
// Elvis operator — supply a default
val displayName = user ?: "Guest"
println("Hello, $displayName!") // Hello, Guest!
// Chained safe calls
val city: String? = null
val upper = city?.trim()?.uppercase()
println("City: $upper") // City: null
// Not-null assertion (use sparingly)
val known: String? = "Kotlin"
println(known!!.length) // 6
// let block — runs only when non-null
user?.let {
println("User found: $it, length=${it.length}")
}
// Null check with smart cast
if (user != null) {
println(user.uppercase()) // user is String here
}
}
Related Resources
Kotlin Reference
Complete tag & property list
Kotlin How-To Guides
Step-by-step practical guides
Kotlin Exercises
Practice what you've learned
More in Kotlin