BudiBadu Logo
Samplebadu

Scala by Example: Variables

Scala 3

Understanding Scala variable declarations with this sample code demonstrating immutable val for functional programming, mutable var for state changes, lazy evaluation for deferred computation, type inference capabilities, and string interpolation syntax.

Code

// Immutable variable (val) - Preferred
val name: String = "Scala"
val version = 3.3 // Type inference

// Mutable variable (var)
var counter = 0
counter = counter + 1

// Lazy values
lazy val heavyComputation = {
  println("Computing...")
  Thread.sleep(1000)
  42
}

// String interpolation
println(s"Language: $name, Version: $version")
println(s"Next: ${counter + 1}")

Explanation

In Scala, variables are defined using either val or var keywords. The val keyword creates an immutable variable similar to final in Java or const in JavaScript, meaning its value cannot be reassigned once initialized. This is the strongly preferred approach in Scala as it promotes functional programming principles, thread safety, and reduces bugs related to unexpected state changes. The var keyword creates a mutable variable that can be reassigned, though its use is generally discouraged except when absolutely necessary.

Scala features a powerful type inference system that can deduce types from assigned values, eliminating the need for explicit type annotations in most cases. While you can explicitly declare types like val x: Int = 10, the compiler can infer the type from the value, leading to concise yet type-safe code. This balance between brevity and static typing is one of Scala's key strengths, providing the safety of statically typed languages without the verbosity.

The lazy val keyword defines a value that is evaluated only when first accessed, not at declaration time. This lazy evaluation is particularly useful for expensive computations, resource initialization, or breaking circular dependencies. The computation runs exactly once on first access, and subsequent accesses return the cached result. String interpolation is supported through the s prefix, allowing variables and expressions to be embedded directly in strings using $variable or expression syntax.

Best practices for Scala variables include:

  • Prefer val over var to maintain immutability and functional programming principles
  • Use type annotations for public APIs and complex expressions where clarity is important
  • Leverage lazy val for expensive initialization that might not always be needed
  • Use string interpolation with s"..." for readable string construction
  • Rely on type inference for local variables to reduce verbosity while maintaining type safety

Code Breakdown

2
val defines a read-only value; reassigning it causes a compiler error.
3
Type inference deduces Double from 3.3 without explicit annotation.
10
lazy val defers evaluation until first access, running computation only once.
17
s"..." enables string interpolation; ${...} allows arbitrary expressions.