Distinguishing val and var
### Lab: Understanding `val` and `var` in Kotlin
#### Objective:
Learn the distinctions between `val` and `var` in Kotlin and understand when to use each for declaring variables.
Topics Covered:
- Immutable variables (`val`) like const: not changable
- Mutable variables (`var`) change / reassign
- Differences between `val` and `var`
- Practical use cases for `val` and `var`
1. **Declaring `val` and `var`**
- Declare a variable using `val` and another using `var`. Assign initial values and try to reassign new values. Observe the results.
```kotlin
// Immutable variable (val)
val pi = 3.14
println("Initial value of pi: $pi")
// Uncommenting the next line will cause a compilation error
// pi = 3.14159
// Mutable variable (var)
var age = 25
println("Initial age: $age")
// Reassigning a new value to the mutable variable
age = 26
println("Updated age: $age")
```
2. **Using `val` for Constants**
- Use `val` to declare a constant value that should not change throughout the program.
```kotlin
val appName = "My Kotlin App"
println("Application Name: $appName")
// Uncommenting the next line will cause a compilation error
// appName = "New App Name"
```
3. **Using `var` for Mutable Data**
- Use `var` to declare a variable whose value will change during the program execution.
```kotlin
var counter = 0
println("Initial counter value: $counter")
// Incrementing the counter
counter += 1
println("Updated counter value: $counter")
```
4. Scope of `val` and `var` in Loops
- Use `val` and `var` inside a loop to understand their behavior within the loop scope.
```kotlin
for (i in 1..5) {
val immutableLoopValue = i
var mutableLoopValue = i
mutableLoopValue += 10
println("Iteration $i: immutableLoopValue = $immutableLoopValue, mutableLoopValue = $mutableLoopValue")
}
```
5. **Using `val` with Collections**
- Declare a collection with `val` and try modifying the collection. Understand that `val` ensures the reference is immutable, not the contents.
```kotlin
val fruits = mutableListOf("Apple", "Banana", "Cherry")
println("Original fruits list: $fruits")
// Adding an element to the collection
fruits.add("Date")
println("Updated fruits list: $fruits")
// Uncommenting the next line will cause a compilation error
// fruits = mutableListOf("Elderberry")
```
6. **Using `var` with Collections**
- Declare a collection with `var` and modify the collection reference.
```kotlin
var vegetables = mutableListOf("Carrot", "Broccoli", "Spinach")
println("Original vegetables list: $vegetables")
// Modifying the collection
vegetables.add("Pepper")
println("Updated vegetables list: $vegetables")
// Reassigning the variable to a new collection
vegetables = mutableListOf("Tomato", "Cucumber")
println("Reassigned vegetables list: $vegetables")
```
7. **Behavior of `val` and `var` with Objects**
- Create a class and use `val` and `var` to declare properties. Understand the difference in behavior.
```kotlin
class Person(val name: String, var age: Int)
val person = Person("Alice", 30)
println("Person: ${person.name}, Age: ${person.age}")
// Uncommenting the next line will cause a compilation error
// person.name = "Bob"
// Modifying the mutable property
person.age = 31
println("Updated Age: ${person.age}")
```
8. **Using `val` for Read-Only Properties**
- Declare a read-only property in a class using `val`.
```kotlin
class Circle(val radius: Double) {
val area: Double
get() = 3.14 * radius * radius
}
val circle = Circle(5.0)
println("Circle radius: ${circle.radius}, Area: ${circle.area}")
// Uncommenting the next line will cause a compilation error
// circle.radius = 6.0
```
9. **Using `var` for Read-Write Properties**
- Declare a read-write property in a class using `var`.
```kotlin
class Rectangle(var length: Double, var width: Double) {
var area: Double
get() = length * width
set(value) {
length = value / width
}
}
var rectangle = Rectangle(4.0, 5.0)
println("Rectangle length: ${rectangle.length}, width: ${rectangle.width}, area: ${rectangle.area}")
// Modifying the properties
rectangle.length = 6.0
println("Updated length: ${rectangle.length}, width: ${rectangle.width}, area: ${rectangle.area}")
```
10. **Understanding `val` in Function Parameters**
- Use `val` in function parameters to ensure the parameters cannot be reassigned within the function.
```kotlin
fun printMessage(message: String) {
println("Message: $message")
// Uncommenting the next line will cause a compilation error
// message = "New Message"
}
printMessage("Hello, Kotlin!")
```
By completing these exercises, students will gain a solid understanding of the differences between `val` and `var` in Kotlin, and they will learn when to use each for declaring variables.