Variables, types and null safety

Learn Kotlin variable types and null safety in Android to master val, var, smart casts, and how to prevent NullPointerExceptions at the edges. About 20 minutes.

Why it matters

  • NullPointerException still 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.

  • val is 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.
  • var is 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:

IdeaKotlinNote
Read-only referencevalNot the same as immutable object
Mutable referencevarPrefer val by default
Compile-time constantconst valTop level, in an object or companion; only primitives and String
Set laterlateinit varNon-null, non-primitive types only
Computed on first useby lazyThread-safe by default
Nullable typeString?Separate type from String
Safe call, Elvis?., ?:Chain them instead of if checks
Safe castas?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

  • val is 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 local var that is not changed between the check and the use (and not changed by a lambda) are fine. A var property of a class is not, because another thread or call could change it. Copy it to a local val first.
  • Platform types (String!) come from Java. Kotlin does not know if they are null. Annotations such as @Nullable and @NonNull are read and turn them into real Kotlin types. Unannotated Java code gets no compile-time checks. Declare the type yourself at the boundary.
  • lateinit throws UninitializedPropertyAccessException if read too early. You can test it with ::name.isInitialized. It does not work for Int, Boolean and other primitives.
  • lazy runs its block once, on first read, and is synchronized by default. Use it for costly values that may never be needed.
  • == is structural equality (calls equals). === is reference equality. Use == in nearly all code.
  • Int overflow wraps silently: Int.MAX_VALUE + 1 is a negative number. For money use whole cents in a Long, not Double.
  • 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: Any is the root of non-null types, Any? is the root of everything, Unit is "no useful result", Nothing is "never returns" (for example throw).
  • Prefer ?: with return or throw for 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

The profile screen that crashed only for some users
  • 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 String quietly held null, and the crash came later, in code that used it.
The fix
  1. Reproduce it with the real payload. Save the failing JSON from the logs and write a unit test that parses it.
  2. Mark fields that can be missing as String?, or give them defaults, and map the DTO to a safe UI model with fallbacks.
  3. Use a parser that fails fast at the boundary. kotlinx.serialization reports a missing required field when parsing, so the error points at the cause.
  4. Keep DTOs (network shape) separate from domain models (what the app trusts).
lateinit read too early
  • Users see a crash on a screen opened from a notification. Normal navigation works.
  • Cause: a Fragment had lateinit var adapter, set in onViewCreated. Only on the notification path, deep-link code in the Fragment's onCreate used the adapter. onCreate runs before onViewCreated, so the read throws UninitializedPropertyAccessException.
The fix
  • Reproduce by launching the screen through the same deep link with adb shell am start.
  • Replace lateinit with a constructor parameter, by lazy, or a nullable that is checked. Keep lateinit for 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 lateinit for 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 val as deep immutability. A val holding a mutable list can still change. Expose List, keep MutableList private.
  • Comparing with === on numbers or strings. Use ==. Reference equality gives surprising results.
  • Storing money in Double. Rounding errors appear. Use cents in a Long or BigDecimal.

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:

  1. Write data class Address(val street: String?, val city: String?) and a function label(address: Address?): String.
  2. It must return "Unknown" when the address, or both fields, are null or blank. Otherwise it returns street, city with a missing part skipped.
  3. Use no !! and no if (x != null) chains. Use ?., ?: and takeIf.
  4. Add a class with a var property and a function that reads it using a local val copy.
  5. 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.

Next: Functions and lambdas