๐ŸŽ“ A1Learner
๐Ÿ”

Kotlin Nullable Types

A nullable type is a type that may hold a value or may hold no value at all. The word null names the absence of a value.

A nullable value can hold null

The type String? allows null as its value. The print shows the word null.

fun main() {
    val name: String? = null
    println(name)
}

A nullable value can hold text

The same type can hold a real text value. The print shows that text.

fun main() {
    val name: String? = "Ana"
    println(name)
}

A check before length

The if check tests that name is not null. Inside the block the length read works and prints 3.

fun main() {
    val name: String? = "Ana"
    if (name != null) {
        println(name.length)
    }
}

Null into a plain String fails

A plain String type has no question mark. Giving it null stops the compile with this error.

fun main() {
    val name: String = null
    println(name)
}

Example

fun main() {
    val first: String? = "Ana"
    val second: String? = null
    println(first)
    println(second)
    if (first != null) {
        println(first.length)
    }
}

Key points

  • nullable: a word for a type that may hold null.
  • String?: a type that may hold text or may hold null.
  • null: the value that means no value is stored.
  • A plain String may never hold null.
  • Use an if check with != null before reading a property of a nullable value.
  • Inside that check, the value works like a plain String.

In this example, first holds the text Ana and second holds null. The first print shows Ana. The second print shows null. The check first != null passes so the last print shows the length of Ana as 3.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Kotlin Playground

Exercise

A program sets a value with the type String? to null and prints it. What prints?