How do I declare variables in Kotlin using val and var?

In Kotlin, you can declare variables using two keywords: val and var. The choice between them depends on whether you want the variable to be immutable or mutable.

1. Declaring Immutable (Read-Only) Variables with val

  • Use val when the value of the variable will not change after it is initialized.
  • The variable becomes read-only (similar to final in Java).

Syntax:

val variableName: Type = value

Example:

val name: String = "John"
// name = "Jane" // This will cause a compilation error

Kotlin can also infer the type automatically if it can be deduced from the value:

val age = 30 // Kotlin infers that 'age' is of type Int

2. Declaring Mutable Variables with var

  • Use var when the value of the variable can change during the program’s lifecycle.
  • The variable becomes mutable.

Syntax:

var variableName: Type = value

Example:

var age: Int = 25
age = 26 // This is allowed because 'age' is mutable

Similarly, type inference can be used:

var firstName = "John" // Kotlin infers that it's a String
firstName = "Jane" // Allowed because 'firstName' is mutable

Key Differences Between val and var

Aspect val var
Mutability Immutable (read-only) Mutable (modifiable)
Reassignment Not allowed Allowed
Use Case When a value should not change When a value needs to change

Additional Examples

Example 1: Declaring Variables with Explicit Types

val city: String = "New York"
var temperature: Double = 25.5
temperature = 30.0 // This is valid

Example 2: Using Type Inference

val country = "USA" // 'country' is inferred to be a String
var isRaining = false // 'isRaining' is inferred to be a Boolean
isRaining = true // Valid because 'isRaining' is mutable

Important Notes

  • For complex objects (like lists and maps), val does not mean the contents of the object cannot change; it just means the variable reference cannot be reassigned.
val list = mutableListOf(1, 2, 3)
list.add(4) // Allowed, because the contents of the list are mutable
// list = mutableListOf(5, 6, 7) // Not allowed, because 'list' is immutable
  • Try to prefer val over var wherever possible to make your code safer and easier to reason about.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.