Kotlin: Variables & Null Safety
What you will learn
How to declare variables with val and var, how Kotlin eliminates null pointer exceptions at compile time, and what "nullable types" means.
val vs var
val name = "Alice" // val = immutable (like final in Java)
var age = 25 // var = mutable
age = 26 // OK
// name = "Bob" // compile error — val cannot be reassigned
val is read-only — once assigned, it cannot change. var is mutable. Prefer val by default; only use var when the value genuinely changes.
Type inference
Kotlin infers types from the initializer. You can also be explicit:
val name: String = "Alice"
val age: Int = 25
Null safety — Kotlin's killer feature
In Kotlin, types are non-nullable by default. A String can never be null. To allow null, add ?:
var name: String? = null // nullable String
name = "Alice" // also OK
// name.length // compile error — name could be null!
name?.length // safe call — returns null if name is null
The safe call operator ?. only calls .length if name is not null; otherwise it returns null. The result type is Int?.
Elvis operator ?:
Provide a default when the value is null:
val len = name?.length ?: 0 // if null, use 0
The !! operator (use sparingly)
val len = name!!.length // throws NullPointerException if name is null
This is the "I know this isn't null" assertion. Avoid it — prefer safe calls and elvis.
Common mistakes
- Thinking
valmakes an object immutable — it only prevents reassignment.val list = mutableListOf(1,2); list.add(3)works. - Using
!!too often — it reintroduces NPEs that Kotlin's type system is designed to prevent. - Forgetting that Kotlin distinguishes
String(never null) fromString?(nullable) — they're different types. - Calling
.lengthdirectly on a nullable variable — Kotlin forces you to use?.or check for null.
Quick check below!