Kotlin has two ways to declare a variable:
val name = "Ada" // read-only (cannot be reassigned)
var age = 30 // mutable (can be reassigned)
age = 31 // OK
// name = "Grace" // ERROR — val cannot be reassigned
Prefer val by default; only use var when a value genuinely needs to change. Kotlin infers types automatically, but you can be explicit:
val score: Int = 100
val price: Double = 19.99
val isActive: Boolean = true
Null safety
Kotlin’s type system distinguishes nullable from non-nullable types at compile time — this is one of its biggest advantages over Java, where a “NullPointerException” (NPE) is one of the most common crash causes.
var name: String = "Ada" // cannot be null
var nickname: String? = null // the ? means this CAN be null
// Safe call — returns null instead of crashing if nickname is null
println(nickname?.length)
// Elvis operator — provide a fallback value
val displayName = nickname ?: "Unknown"
The compiler will not let you call a method directly on a nullable type without handling the null case first — this catches an entire category of crashes before your app ever runs.
- Image
- SKU
- Rating
- Price
- Stock
- Availability
- Add to cart
- Description
- Content
- Weight
- Dimensions
- Additional information