Kotlin functions & null safety
Write expressive functions and handle missing values without surprises.
What you’ll learn
Before you start
- Basic programming concepts
1. Declare a function
Kotlin places parameter types after names. A function with a block body declares its return type after the closing parenthesis.
fun greeting(name: String?): String {
val displayName = name?.trim()?.takeIf { it.isNotEmpty() } ?: "developer"
return "Hello, $displayName!"
}2. Model missing values
String? allows null. ?. skips the call when its receiver is null. takeIf keeps the trimmed name only when it is nonempty. ?: supplies a fallback when the chain yields null.
3. Check edge cases
Call the function with "Ada", null, and " " in a Kotlin project. Reason about the result before running it. There is no Kotlin runtime in this website's playground.
Expected output
The calls return Hello, Ada!, Hello, developer!, and Hello, developer!, respectively.
Troubleshooting
Avoid !! unless you can prove the value cannot be null. A non-null assertion moves a type-safety problem into a runtime crash.