Skip to content
LumenaryAcademy
Foundations 55 min

Values, types and null safety

val and var, Kotlin's basic types and explicit conversions, strings and equality, and the type system's most famous feature, the separation of nullable and non-null types.

Code tested · 3AI-draftedAwaiting review by a computer scientist
MotivationH

The billion-dollar mistake

In 1965 the computer scientist Tony Hoare added the null reference to the language ALGOL W, because it was easy to implement. Decades later he called it his "billion-dollar mistake": in almost every language that copied the idea, any reference might secretly be null, and the program crashes when it uses one. Java inherited it. A NullPointerException is the single most common crash in Java programs, and countless lines of defensive if (x != null) code exist only to avoid it.

Kotlin's answer is to make "might be missing" part of the type. A variable of type String always holds a string. A variable that may hold no string has a different type, String?, and the compiler will not let you call .length on it until you have dealt with the missing case. Null is not banned; it is tracked. The effect on day-to-day code is large: whole categories of crash become compile errors, and the places where a value really can be absent are visible in every signature.

This lesson starts with the rest of Kotlin's basic types (numbers, characters, strings) and how they differ from Java's, then spends most of its time on null safety, which shapes how idiomatic Kotlin looks.

DefinitionsH

Variables and basic types

Definition— val and var

val declares a read-only variable: assigned once, never reassigned. var declares a mutable one. The type may be written (val year: Int = 2026) or inferred (val year = 2026). Idiomatic Kotlin uses val unless a variable must change.

Kotlin's basic types look like Java's, written with capital letters, and on the JVM most compile to Java primitives when they cannot be null:

Kotlin typeSizeExample literalsNotes
Byte, Short8, 16 bits7.toByte()Rarely used directly
Int32 bits42, 1_000_000, 0xFF, 0b1010The default for whole numbers
Long64 bits3_000_000_000, 42LInferred when the value does not fit an Int
Double, Float64, 32 bits2.5, 6.02e23, 2.5fIEEE 754 binary floating point
Boolean—true, false
Char16 bits'A', 'ñ', '\n'A character, not a number
String—"text", """raw"""Immutable, as in Java
UInt, ULong, ...32, 64 bits255u, 42uLUnsigned integers

Two differences from Java matter immediately. First, there are no implicit widening conversions: an Int is never silently turned into a Long or a Double when assigned. You call toLong(), toDouble(), toInt() and so on. Arithmetic between different types is allowed (small / 5.0 is a Double), but assignments must match exactly. Second, Char is not a number. You can add an integer to a character to move along the alphabet, but you convert to a code explicitly with .code.

Definition— Nullable type

For every type T, the type T? contains all the values of T plus null. A value of type T (with no question mark) can never be null. The compiler allows member access on a T? only through null-safe operators, or after a check proves the value is not null.

Definition— Any, Unit and Nothing

Any is the supertype of every non-null type (like Java's Object); Any? is the top of the whole hierarchy. Unit is the type of functions that return no interesting value (like Java's void, but a real type with one value). Nothing is the type of expressions that never complete normally, such as throw or a function that always throws; it has no values at all.

Worked examplesH

Numbers and characters

kotlin
fun main() {
    // Integer arithmetic
    println(7 / 2)                    // Int / Int is Int
    println(-7 / 2)
    println(-7 % 2)
    println(Math.floorMod(-7, 2))     // or (-7).mod(2) in Kotlin
    println((-7).mod(2))
    println(7.0 / 2)

    // Overflow wraps, just as on the JVM
    println(Int.MAX_VALUE + 1)
    println(Int.MAX_VALUE.toLong() + 1)

    // No implicit widening: conversions are explicit
    val small: Int = 42
    val big: Long = small.toLong()
    val ratio: Double = small / 5.0
    println("$big $ratio ${ratio.toInt()}")

    // Chars are not numbers in Kotlin, but you can move along the alphabet
    println('A' + 2)
    println('A'.code)
    println(('a'..'e').joinToString(""))

    // Unsigned types and literals
    val mask: UInt = 0xFFu
    println(mask * 2u)
    println(1_000_000 * 3L)
}
text
3
-3
-1
1
1
3.5
-2147483648
2147483648
42 8.4 8
C
65
abcde
510
3000000

Kotlin/JVM uses the JVM's arithmetic, so the familiar rules apply: integer division truncates toward zero, % takes the sign of the left operand (use mod for a result that is never negative with a positive divisor), and Int arithmetic overflows silently. Kotlin did not change that, for speed and Java compatibility, so the habit of reaching for Long (or Math.addExact) when values can grow large still applies.

The conversion line shows the explicit style: small.toLong() to widen, ratio.toInt() to truncate. Writing val big: Long = small would not compile. It feels fussy at first, and then you notice that a whole class of Java surprises (an int multiplied before being widened to long, an equality test between an Integer and a Long that is always false) cannot happen.

'A' + 2 is 'C': adding an Int to a Char gives a Char. 'A'.code gives the numeric code, 65. 'a'..'e' is a range of characters. Unsigned types (UInt, ULong, UByte, UShort) exist for bit manipulation and binary protocols; use signed types everywhere else.

Worked examplesH

Strings, equality and the special types

kotlin
fun fail(message: String): Nothing = throw IllegalStateException(message)

fun describe(x: Any): String = when (x) {
    is Int -> "an Int, doubled ${x * 2}"           // smart cast to Int
    is String -> "a String of length ${x.length}"  // smart cast to String
    else -> "something else: ${x::class.simpleName}"
}

fun main() {
    // == compares contents (it calls equals); === compares identity
    val a = "lumen"
    val b = StringBuilder("lu").append("men").toString()
    println("${a == b} ${a === b}")

    // Raw strings: no escapes, and trimIndent removes the common indentation
    val poem = """
        Roses are red,
          violets are blue,
        C:\path\needs\no\escapes
    """.trimIndent()
    println(poem)

    // Multi-dollar interpolation (Kotlin 2.2): $$ marks templates, so a lone $ is literal
    val price = 42
    println($$"""{"price": "$$$price", "currency": "$"}""")

    // Any is the root of all non-null types
    println(describe(21))
    println(describe("Kotlin"))
    println(describe(listOf(1, 2)))

    // Unit is the type of "no interesting value"; Nothing is the type of "never returns"
    val result: Unit = println("println returns Unit")
    println(result)
    val value: Int = "17".toIntOrNull() ?: fail("not a number")
    println(value + 1)
}
text
true false
Roses are red,
  violets are blue,
C:\path\needs\no\escapes
{"price": "$42", "currency": "$"}
an Int, doubled 42
a String of length 6
something else: ArrayList
println returns Unit
kotlin.Unit
18

Equality. In Kotlin, == means structural equality: a == b calls a.equals(b) (and handles null safely on either side). === means referential equality, the same object. So the string-comparison trap that catches Java beginners does not exist in Kotlin: == on strings compares their characters. The two strings here have equal contents but are different objects.

Raw strings in triple quotes contain no escape sequences (the backslashes are literal) and can span lines; trimIndent() removes the indentation common to all lines, so the literal can be indented with the code. When a string must contain many literal dollar signs, such as JSON or a template language, Kotlin 2.2's multi-dollar interpolation helps: in a string prefixed with two dollar signs, only two dollar signs start a template, so a single one is ordinary text. That is why the output contains both the literal $ and the value 42.

Any and smart casts. describe accepts anything non-null. Inside is Int ->, the compiler knows x is an Int and lets you multiply it; inside is String -> it knows x is a String. This is a smart cast: after a type check, the variable is treated as the checked type, with no cast written. You will see when properly in the next lesson.

Unit and Nothing. println returns Unit, a real object that prints as kotlin.Unit. fail is declared to return Nothing, meaning it never returns normally. That lets the compiler accept "17".toIntOrNull() ?: fail(...) as an Int: the right side never produces a value, so the whole expression can only ever produce the left side's Int.

Worked examplesH

Null safety in practice

The program below uses a few data classes, Kotlin's one-line classes for holding data (they are the subject of Classes, data classes, sealed classes and objects). A customer may have no email and no address, and an address may have no postcode, and the types say so:

kotlin
data class Address(val city: String, val postcode: String?)
data class Customer(val name: String, val email: String?, val address: Address?)

fun shippingLabel(c: Customer): String {
    // Safe calls (?.) stop at the first null; the Elvis operator (?:) supplies a default
    val city = c.address?.city ?: "no address"
    val postcode = c.address?.postcode ?: "-"
    return "${c.name}, $city $postcode"
}

fun emailDomain(c: Customer): String? {
    val email = c.email ?: return null          // Elvis with return: leave early if missing
    return email.substringAfter('@')            // smart cast: email is a String here
}

fun main() {
    val customers = listOf(
        Customer("Amara", "amara@example.org", Address("Accra", "GA-123")),
        Customer("Bao", null, Address("Hanoi", null)),
        Customer("Chidi", "chidi@example.com", null),
    )
    for (c in customers) {
        println(shippingLabel(c) + " | domain: " + (emailDomain(c) ?: "none"))
    }

    // Parsing returns null instead of throwing
    val inputs = listOf("42", "seven", "-3", "")
    val numbers: List<Int?> = inputs.map { it.toIntOrNull() }
    println(numbers)
    println(numbers.filterNotNull().sum())

    // let runs a block only when the value is not null
    val maybe: String? = "Kotlin"
    maybe?.let { println("length of $it is ${it.length}") }

    // Smart cast after an explicit check
    val text: String? = if (numbers.size > 3) "checked" else null
    if (text != null) {
        println(text.uppercase())               // no ?. needed: the compiler knows it is not null
    }

    // !! says "I am sure this is not null" and throws if you are wrong
    val missing: String? = null
    try {
        println(missing!!.length)
    } catch (e: NullPointerException) {
        println("NullPointerException from !!")
    }

    // Safe cast: as? gives null instead of throwing
    val anything: Any = 3.14
    val asText: String? = anything as? String
    println(asText ?: "not a string")
}
text
Amara, Accra GA-123 | domain: example.org
Bao, Hanoi - | domain: none
Chidi, no address - | domain: example.com
[42, null, -3, null]
39
length of Kotlin is 6
CHECKED
NullPointerException from !!
not a string

The toolkit, from most to least used:

  • Safe call ?.: c.address?.city is the city if address is not null, and null otherwise. Chains short-circuit at the first null, so a?.b?.c never crashes.
  • Elvis ?:: x ?: fallback is x unless x is null, in which case it is fallback. The fallback can be a value, or return, or throw, which gives the "guard clause" in emailDomain: if there is no email, leave now; after that line, email is a plain String.
  • Smart casts: after if (text != null), the compiler treats text as String inside the block. Smart casts work on local variables and on val properties of the same module; they do not work on var properties that another thread could change between the check and the use, and the compiler will tell you so.
  • let: maybe?.let { ... } runs the block only for a non-null value, which it calls it. It is handy at the end of a safe-call chain; for simple cases an if is just as clear.
  • Standard functions that return null instead of throwing: toIntOrNull, firstOrNull, getOrNull, the map lookup map[key]. Kotlin's library offers an OrNull variant of almost everything that can fail, and filterNotNull/mapNotNull to clean up collections of nullable values.
  • Safe cast as? returns null when the cast would fail, instead of throwing a ClassCastException.
  • Not-null assertion !! converts a T? to T and throws a NullPointerException if it was null. It is an escape hatch, and every !! in a code review invites the question "why are you sure?".

What the compiler rejects is just as instructive. Both of these lines are compile errors:

kotlin
fun lengthOf(maybe: String?): Int {
    return maybe.length
}
// error: only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of type 'String?'.

val n: Int = null
// error: null cannot be a value of a non-null type 'Int'.
ExplanationH

Null safety as professionals use it

Design with non-null types first. Make a property or parameter nullable only when "absent" is a real, meaningful state (a customer genuinely may have no email). Then the question mark in the type is documentation that the compiler checks. Making everything nullable "to be safe" just moves the problem around.

Push nulls to the edges. Data that comes from outside (user input, JSON, a database, Java code) may be missing. Convert and validate it once, at the boundary, into non-null types, perhaps with ?: throw IllegalArgumentException(...) or requireNotNull(...), and let the rest of the program work with values it can trust.

Avoid !! in production code. There are legitimate uses (a test, or a value that a framework guarantees to have set), but each one is a claim the compiler cannot check. Prefer ?: with a clear error: config["port"] ?: error("port is not configured") fails with a message that explains itself, while config["port"]!! produces a bare NullPointerException.

Know about platform types. Java code has no question marks, so Kotlin cannot know whether a value from a Java method may be null. It gives such values a platform type, shown in error messages as String!, and lets you treat them as either nullable or not. If you treat one as non-null and Java returns null, you get an exception at that point. Many Java libraries now carry nullability annotations (such as JSpecify's @Nullable) that Kotlin reads to give proper types. Java interoperability, Gradle and testing returns to this.

lateinit for "set later, before use". A non-null var property that a framework or a setup method initialises after construction can be declared lateinit var service: Service. Reading it before it is set throws a clear UninitializedPropertyAccessException. Use it sparingly; constructor parameters are better when possible.

Common misconceptionsH

Common misconceptions

Misconception

"Kotlin has no null." It has null, and String? can hold it. What Kotlin removes is the possibility that a String holds null unexpectedly.

Misconception

"== in Kotlin works like == in Java." For objects it works like Java's equals, comparing contents, and it is null-safe. Kotlin's === is Java's == for objects.

Misconception

"An Int will be widened to a Long automatically, as in Java." Kotlin never converts numbers implicitly on assignment. Call toLong().

Misconception

"!! is how you get rid of compiler errors about nullability." It silences the compiler by promising something it cannot check. Fix the type, add a check, or provide a default with ?: instead.

Exercises

Exercises

1. Values, types and null safety

Warm-upComputational

What does this program print?

fun main() {
    val words = listOf("sun", null, "moonlight")
    println(words.map { it?.length ?: 0 })
}

2. Values, types and null safety

Warm-upComputational

What does this program print?

fun main() {
    println(listOf("4", "four", "40").mapNotNull { it.toIntOrNull() }.sum())
}

3. Values, types and null safety

StretchComputational

What does this program print? (The code of 'x' is 120.)

fun main() {
    println("" + ('x' + 1) + ('x'.code + 1))
}

4. Values, types and null safety

CoreComputational

What does this program print? (Int.MAX_VALUE is 2147483647.)

fun main() {
    println(Int.MAX_VALUE + 2)
}

5. Values, types and null safety

CoreHuman

Inside a function with a parameter maybe: String?, which of these lines compile? Choose all that apply.

Choose all that apply

6. Values, types and null safety

CoreHuman

A configuration map returns String? for a key. Which is the best way to read a required setting?

Choose one

Further reading and resources