Variables in Kotlin are used to store data that can be referenced and manipulated within a program. Kotlin provides a flexible and type-safe way to declare variables with different levels of mutability and types.
val):
val variableName: Type = valuevar):
var variableName: Type = valueval):val name: String = "John"
val age: Int = 25
// name = "Doe" // Error: Val cannot be reassigned
var):var city: String = "New York"
var temperature: Int = 30
city = "Los Angeles" // This is allowed
Kotlin has type inference, meaning the type can be automatically inferred by the compiler based on the assigned value, so specifying the type is optional if it's clear from the context.
val name = "John" // Compiler infers String
var age = 25 // Compiler infers Int