Variables, types and null safety
Why it matters
NullPointerExceptionstill happens in Kotlin apps. It comes from the edges: JSON, Java libraries,lateinit,!!.- Null safety is checked by the compiler, but only for code the compiler can see. Data from outside can break the promise.
- Questions on
val,lateinit,lazy,?.,?:and smart casts appear in almost every Kotlin interview. - Every later lesson (classes, Flow, Compose state) assumes you read types like
String?without thinking.
The simple explanation
Think of a parcel locker. A normal locker (String) always has a parcel inside. A locker marked "may be empty" (String?) must be checked before you reach in.
valis a locker that is sealed after the first fill. You cannot swap the parcel. The parcel itself may still be changed if it is a mutable object.varis a locker you can refill at any time.?.means "open it only if there is a parcel, otherwise give me null".?:means "if empty, use this default".!!means "I promise it is full". If you are wrong, the app crashes.
The real names:
| Idea | Kotlin | Note |
|---|---|---|
| Read-only reference | val | Not the same as immutable object |
| Mutable reference | var | Prefer val by default |
| Compile-time constant | const val | Top level, in an object or companion; only primitives and String |
| Set later | lateinit var | Non-null, non-primitive types only |
| Computed on first use | by lazy | Thread-safe by default |
| Nullable type | String? | Separate type from String |
| Safe call, Elvis | ?., ?: | Chain them instead of if checks |
| Safe cast | as? | Gives null instead of ClassCastException |
Types are inferred, but numbers never widen on their own. An Int is not accepted where a Long is expected. Call toLong().
Notes
valis a read-only reference, not a frozen object.val list = mutableListOf(1)can still change inside.- A smart cast works only when the compiler can prove the value cannot change between the check and the use. Local
val, parameters, and a localvarthat is not changed between the check and the use (and not changed by a lambda) are fine. Avarproperty of a class is not, because another thread or call could change it. Copy it to a localvalfirst. - Platform types (
String!) come from Java. Kotlin does not know if they are null. Annotations such as@Nullableand@NonNullare read and turn them into real Kotlin types. Unannotated Java code gets no compile-time checks. Declare the type yourself at the boundary. lateinitthrowsUninitializedPropertyAccessExceptionif read too early. You can test it with::name.isInitialized. It does not work forInt,Booleanand other primitives.lazyruns its block once, on first read, and is synchronized by default. Use it for costly values that may never be needed.==is structural equality (callsequals).===is reference equality. Use==in nearly all code.Intoverflow wraps silently:Int.MAX_VALUE + 1is a negative number. For money use whole cents in aLong, notDouble.- On the JVM, Kotlin inserts null checks on non-null parameters of non-private functions. A null from Java or bad JSON often fails later and far from the cause.
- Useful types:
Anyis the root of non-null types,Any?is the root of everything,Unitis "no useful result",Nothingis "never returns" (for examplethrow). - Prefer
?:withreturnorthrowfor early exit:val id = user.id ?: return.
Code example
An API user where the name or email may be missing. We build a display name and never use !!.
const val MAX_NAME_LENGTH = 40 // compile-time constant
data class UserDto(
val id: Long,
val name: String?, // the server may send null
val email: String?,
)
fun displayName(user: UserDto): String {
// ?. skips the call on null, ?: supplies the fallback
val fromName = user.name?.trim()?.takeIf { it.isNotEmpty() }
val fromEmail = user.email?.substringBefore('@')
return (fromName ?: fromEmail ?: "Guest").take(MAX_NAME_LENGTH)
}
class Profile {
var user: UserDto? = null // a var property: no smart cast
fun greeting(): String {
// Copy to a local val. Now the compiler knows it cannot change.
val current = user ?: return "Loading..."
return "Hello, " + displayName(current)
}
}
class Report {
// Costly work runs once, on first read.
val summary: String by lazy { "built once" }
}Try it in plain Kotlin. The same rules apply on Android.
data class UserDto(val id: Long, val name: String?, val email: String?)
fun displayName(user: UserDto): String {
val fromName = user.name?.trim()?.takeIf { it.isNotEmpty() }
val fromEmail = user.email?.substringBefore('@')
return fromName ?: fromEmail ?: "Guest"
}
class Holder {
var text: String? = null
fun length(): Int {
val t = text ?: return -1 // local copy, then smart cast
return t.length
}
}
fun main() {
println(displayName(UserDto(1, " Sara ", null))) // Sara
println(displayName(UserDto(2, " ", "lee@mail.com"))) // lee
println(displayName(UserDto(3, null, null))) // Guest
val h = Holder()
println(h.length()) // -1
h.text = "droid"
println(h.length()) // 5
val big = Int.MAX_VALUE
println(big + 1) // wraps to a negative number
println(big.toLong() + 1) // 2147483648
}In production
- Crash reports show a null-related crash on the profile screen for a small share of users. QA never sees it.
- The data class had
val name: String, but the server sometimes omitted the field. The app used Gson. - Cause: Gson fills fields by reflection and does not respect Kotlin null safety. A non-null
Stringquietly held null, and the crash came later, in code that used it.
- Reproduce it with the real payload. Save the failing JSON from the logs and write a unit test that parses it.
- Mark fields that can be missing as
String?, or give them defaults, and map the DTO to a safe UI model with fallbacks. - Use a parser that fails fast at the boundary.
kotlinx.serializationreports a missing required field when parsing, so the error points at the cause. - Keep DTOs (network shape) separate from domain models (what the app trusts).
- Users see a crash on a screen opened from a notification. Normal navigation works.
- Cause: a Fragment had
lateinit var adapter, set inonViewCreated. Only on the notification path, deep-link code in the Fragment'sonCreateused the adapter.onCreateruns beforeonViewCreated, so the read throwsUninitializedPropertyAccessException.
- Reproduce by launching the screen through the same deep link with
adb shell am start. - Replace
lateinitwith a constructor parameter,by lazy, or a nullable that is checked. Keeplateinitfor values that the framework sets before your code runs, such as injected fields.
Common mistakes
- Sprinkling
!!to make the compiler quiet. It turns a compile error into a runtime crash. Use?:,?., or fix the type. - Using
lateinitfor convenience. If you cannot say who sets it before first use, make it nullable or pass it in. - Trusting JSON types. A non-null field in a DTO is a hope, not a check, with some parsers.
- Treating
valas deep immutability. Avalholding a mutable list can still change. ExposeList, keepMutableListprivate. - Comparing with
===on numbers or strings. Use==. Reference equality gives surprising results. - Storing money in
Double. Rounding errors appear. Use cents in aLongorBigDecimal.
Interview questions
Answer out loud first. Then reveal the answer and compare it at each depth.
“What is the difference between val and var, and between val and const val?”
“How does null safety work, and where can it fail?”
“Why does a smart cast sometimes not compile?”
“When would you use lazy and when lateinit?”
Quiz
Given val name: String? = null, what does println(name?.length) print?
Which value usually cannot be smart cast after a null check?
Which type can be declared with lateinit?
What is true about const val?
0 of 4 answered
Mini task
Open the Playground above, or a Kotlin file in your project, and do this in 15 minutes:
- Write
data class Address(val street: String?, val city: String?)and a functionlabel(address: Address?): String. - It must return
"Unknown"when the address, or both fields, are null or blank. Otherwise it returnsstreet, citywith a missing part skipped. - Use no
!!and noif (x != null)chains. Use?.,?:andtakeIf. - Add a class with a
varproperty and a function that reads it using a localvalcopy. - Test five inputs with
println.
You are done when all five outputs match what you predicted before running, and you can say why a var property cannot be smart cast.