Null safety, val and data classes in Kotlin
How nullable types and the ?., ?: and !! operators work, plus val versus var and what data classes give you.
Kotlin's type system is designed to stop null pointer errors at compile time. Most Kotlin screening questions check whether you can read nullable code and predict exactly what it returns.
Nullable and non-null types
A plain String can never hold null. Add a question mark, String?, and the variable may be null, but the compiler will no longer let you call its members directly.
val city: String? = null
println(city?.length) // null
println(city?.length ?: 0) // 0
println(city!!.length) // throws NullPointerException
?.calls the member only if the value is not null; otherwise the whole expression is null.?:, the Elvis operator, supplies a fallback when the left side is null.!!asserts that the value is not null and throws if it is. Use it rarely.
After an explicit check such as if (city != null), the compiler smart-casts the value to a non-null type inside that block, so you can use it directly. city?.let { ... } runs a block only when the value is present.
val and var
val declares a read-only reference that cannot be reassigned, while var can be reassigned. A val holding a mutable list can still have items added, because the list changes, not the reference. Prefer val by default and switch to var only when you need to.
val items = mutableListOf(1, 2)
items.add(3) // fine
items = mutableListOf() // compile error
Data classes
Marking a class with data generates equals(), hashCode(), toString(), copy() and component functions from the properties in the primary constructor.
data class Job(val title: String, val city: String)
val a = Job("Tester", "Pune")
val b = a.copy(city = "Manila")
println(a) // Job(title=Tester, city=Pune)
println(a == b) // false, city differs
val c = Job("Tester", "Pune")
println(a == c) // true, same content
println(a === c) // false, different objects
In Kotlin, == calls equals(), and === checks whether two references point to the same object.
Checklist
- Mark which variables are nullable.
- For each ?. chain, ask what happens if the first value is null.
- Look for a ?: fallback at the end.
- Check whether == or === is being used.
More in Programming