Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Variable

Introduction to var and val

  • Definition and Usage:
    • val is used to declare an immutable variable. Once initialized, its value cannot be changed.
    • var is used for mutable variables. Its value can be reassigned after initialization.
  • Syntax:
    val immutableVariable: Type = initialValue
    var mutableVariable: Type = initialValue
    
  • Key Difference: Mutability vs. immutability.







val - Immutable Variables

  • Advantages:
    • Encourages functional programming style.
    • Safer to use in concurrent or multi-threaded environments.
    • Helps in avoiding side effects, making code more predictable.
  • Use Cases:
    • When the value does not need to change after initialization.
    • For constants or read-only properties.
    • In method parameters to ensure they remain unchanged.
  • Examples:
    val pi: Double = 3.14
    val greeting: String = "Hello, Scala!"
    







var - Mutable Variables

  • Advantages:
    • Provides flexibility when a variable’s value needs to change, e.g., counters, stateful objects.
  • Disadvantages:
    • Can lead to code that is harder to understand and maintain.
    • Increased risk of errors in concurrent or multi-threaded environments.
  • Use Cases:
    • When a variable’s value needs to be updated, such as in loops or when reacting to external inputs.
    • State management within an object.
  • Examples:
    var counter: Int = 0
    var message: String = "Initial message"
    







Best Practices

  • Prefer val over var:
    • Use val by default to make your code more functional, predictable, and thread-safe.
  • Limit the use of var:
    • Restrict var usage to local scopes or cases where mutability is necessary.
    • Consider using immutable collections or structures to manage state changes more safely.
  • Performance Considerations:
    • Immutable objects can sometimes lead to increased memory usage due to the need for creating new objects instead of updating existing ones. However, the benefits of immutability in terms of code clarity and safety often outweigh these concerns.







Transitioning from Mutable to Immutable Patterns

  • Strategies:
    • Use immutable collections and operations that return new collections instead of modifying the original.
    • Apply functional programming techniques, such as mapping and reducing over collections, instead of imperative loops with mutable state.
  • Case Study: Refactoring an imperative loop to a functional style.
  • Example: Converting a loop that sums numbers using var to a functional style using val and collection methods.