In Kotlin, declaring variables is straightforward and flexible. You can declare variables using the var
keyword for mutable variables (those that can be reassigned) or the val
keyword for immutable variables (those that cannot be reassigned once initialized). Here’s a detailed explanation of both:
Declaring Mutable Variables (var
)
Mutable variables are those whose value can change during the execution of the program. They are declared using the var
keyword.
kotlinCopy codevar age: Int = 25
age = 26 // This is allowed
Declaring Immutable Variables (val
)
Immutable variables are those whose value cannot change once they are initialized. They are declared using the val
keyword.
kotlinCopy codeval name: String = "John"
// name = "Doe" // This will cause a compilation error
Type Inference
Kotlin has a strong type inference system, which means you can often omit the type declaration if it’s clear from the context.
kotlinCopy codevar city = "New York" // Kotlin infers that city is of type String
val temperature = 75 // Kotlin infers that temperature is of type Int
Declaring Variables without Initialization
If you declare a variable without initializing it, you must specify the type explicitly.
kotlinCopy codevar country: String
country = "USA"
val pi: Double
pi = 3.14159
Nullable Variables
In Kotlin, variables can be declared as nullable by using the ?
after the type. This allows the variable to hold a null value.
kotlinCopy codevar address: String? = null
address = "123 Main St"
Example Usage
Here is a complete example showing different types of variable declarations:
kotlinCopy codefun main() {
// Mutable variable
var age: Int = 30
age = 31
// Immutable variable
val name: String = "Alice"
// Type inference
var city = "San Francisco"
val temperature = 68
// Nullable variable
var address: String? = null
address = "456 Elm St"
println("Name: $name, Age: $age, City: $city, Temperature: $temperature, Address: $address")
}
Summary
- Use
var
for variables that need to change. - Use
val
for variables that should remain constant. - Kotlin’s type inference often allows you to omit explicit type declarations.
- Use
?
to allow a variable to hold a null value.