Careeroza
Real World Example
Optional Profile Fields
A Swiggy or Zomato user profile comes from an API where many fields are optional: the user may not have set a name, an alternate phone or a landmark. With Kotlin's nullable types the compiler forces you to handle every missing value, so the app shows sensible defaults instead of crashing.
Example
Building an address card from optional data:
fun addressCard(name: String?, flat: String, landmark: String?, altPhone: String?): String {
val displayName = name?.trim()?.takeIf { it.isNotEmpty() } ?: "Customer"
val landmarkLine = landmark?.let { "Near $it" } ?: "No landmark"
val contact = altPhone ?: "not provided"
return "$displayName | $flat | $landmarkLine | Alt phone: $contact"
}
fun main() {
println(addressCard("Asha", "Flat 402, Lake View", "Inorbit Mall", "9988776655"))
println(addressCard(null, "H.No 12-3, Ameerpet", null, null))
println(addressCard(" ", "B-17, Sector 62", "Metro Station", null))
}Output
Asha | Flat 402, Lake View | Near Inorbit Mall | Alt phone: 9988776655 Customer | H.No 12-3, Ameerpet | No landmark | Alt phone: not provided Customer | B-17, Sector 62 | Near Metro Station | Alt phone: not provided
In an Android App
On Android, values from an Intent, a saved bundle or a JSON response are often nullable. A typical pattern:
val orderId: String? = intent.getStringExtra("order_id")
orderId?.let { id ->
viewModel.loadOrder(id)
} ?: run {
showError("Order not found")
finish()
}Exercise: Write a function greeting(name: String?): String that returns "Hello, NAME" in uppercase, or "Hello, GUEST" when the name is null. Use ?. and ?:.
Show answer
fun greeting(name: String?): String = "Hello, ${name?.uppercase() ?: "GUEST"}"
fun main() {
println(greeting("ravi")) // Hello, RAVI
println(greeting(null)) // Hello, GUEST
}