Ruang penulis
← Kembali ke jurnal
Kotlin

How do I declare nullable variables using `?` in Kotlin?

In Kotlin, you declare a nullable variable by adding ? after the type. var name: String? = null This means name can hold either a String value or null. Examples: var age: Int? = null age = 25 val email: String? = "user@example.com" val phone: String? = null Without ?, Kotlin does not allow null: […]

DWayan · 26 Jun 2026 · 1 menit baca

Artikel oleh Wayan · Sumber: Kode Java ↗

Terjemahan artikel ini belum tersedia. Isi asli ditampilkan.

In Kotlin, you declare a nullable variable by adding ? after the type.

var name: String? = null

This means name can hold either a String value or null.

Examples:

var age: Int? = null
age = 25

val email: String? = "user@example.com"
val phone: String? = null

Without ?, Kotlin does not allow null:

var name: String = null // Error

With ?, you must handle possible null safely:

val name: String? = null

println(name?.length) // Safe call, prints null instead of crashing

You can also provide a default value with the Elvis operator ?::

val name: String? = null
val length = name?.length ?: 0

println(length) // 0

So the basic pattern is:

var variableName: Type? = null
← Jelajahi catatan lainnya