Scala – Var, Val

  • date 19th February, 2021 |
  • by Prwatech |
  • 0 Comments

Variables in Scala

 

Scala has two types of variables

  • Var - creates an Immutable variable(i.e final in java)
  • Val – creates a mutable variable(i.e you can reassign a value)

The distinction among val and var is that val makes a variable permanent, like final in Java — and var makes a variable alterable. Since val fields can't change but var value can be reassign .

 

  1. Immutable: Declared using val, immutable in Scala cannot be reassigned once initialized. This promotes functional programming principles by ensuring predictability and avoiding unintended side effects.

  2. Mutable: Declared using var, mutable variables in Scala can be reassigned after initialization. While mutable variables offer flexibility for scenarios requiring state changes, they be use judiciously to maintain code clarity and avoid mutable state-related issues.

  3. Type Inference: Scala's type inference system allows developers to omit explicit type annotations when declaring variables, reducing boilerplate and improving code readability while retaining strong static typing.

  4. Scope and Lifetime: Scala variables have lexical scope, meaning their visibility is determin by the block or function in which they are defin. Variables are typically garbage-collect when they go out of scope, managing memory efficiently.

  5. Pattern Matching: Scala's powerful pattern matching capabilities extend to variables, enabling concise and expressive handling of data based on its structure and content.

Var

1)

2)

3)

Val

1)

2)

3)

 

Quick Support

image image