Immutability and Side Effects
Understand the importance of immutability in functional programming and how to manage side effects effectively.
Immutable by Design
Welcome to our lesson on Immutability and Side Effects! These are core concepts in functional programming (FP) that help us write cleaner, more predictable code.
In FP, we prefer to work with immutable data. This means once a piece of data is created, it cannot be changed. Think of it like a photograph – you can look at it, but you can't alter the original moment it captured.
val vs. var in Scala
Scala makes it easy to declare immutable values using the val keyword. This is a constant reference that cannot be reassigned after its initial definition. For mutable variables, you'd use var.
Let's see the difference:
object Main {
def main(args: Array[String]): Unit = {
// Immutable value
val greeting = "Hello"
// greeting = "Hi" // This would cause a compile error!
// Mutable variable
var count = 0
count = 1 // This is allowed
println(greeting)
println(count)
}
}All lessons in this course
- Functions as First-Class Values
- Higher-Order Functions & Currying
- Immutability and Side Effects