
- Scala - Home
- Scala - Overview
- Scala - Features
- Scala - Environment Setup
- Scala - Build Tool (SBT)
- Scala - REPL
- Scala - Dot & Dotty
- Scala - Basic Syntax
- Scala - Hello World Program
- Scala - Identifiers
- Scala - Keywords
- Scala - Comments
- Scala - Code Blocks
- Scala - Semicolon
- Scala - Constructs
- Scala - Expressions
- Scala - Input and Output
- Scala - Optional Braces
- Scala - Underscore (_)
- Data Types and Variables
- Scala - Data Types
- Scala - Type Bounds
- Scala - Context Bound
- Scala - Variances
- Scala - Type Hierarchy
- Scala - Variables
- Scala - Variable Scopes
- Scala - Literals
- Scala - Numeric Types
- Scala - Boolean Types
- Scala - Char Type
- Scala - Unit Types
- Scala - Strings
- Scala - Arrays
- Scala - Null Type
- Scala - Nothing
- Scala - Any Type
- Scala - AnyRef Type
- Scala - Unified Types
- Scala - Dates and Times
- Scala - Ranges
- Scala - Multidimensional Arrays
- Scala - WrappedArray
- Scala - StringBuilder
- Scala - String Interpolation
- Scala - StringContext
- Scala - Type Casting
- Scala var vs val
- Scala Operators
- Scala - Operators
- Scala - Rules for Operators
- Scala - Arithmetic Operators
- Scala - Relational Operators
- Scala - Logical Operators
- Scala - Bitwise Operators
- Scala - Assignment Operators
- Scala - Operators Precedence
- Scala - Symbolic Operators
- Scala - Range Operator
- Scala - String Concatenation Operator
- Scala Conditional Statements
- Scala - IF ELSE
- Scala - IF-ELSE-IF-ELSE Statement
- Scala - Nested IF-ELSE Statement
- Scala Loop Statements
- Scala - Loop Statements
- Scala - while Loop
- Scala - do-while Loop
- Scala - Nested Loops
- Scala - for Loop
- Scala - break Statement
- Scala - yield Keyword
- Scala Classes & Objects
- Scala - Classes & Objects
- Scala - Constructors
- Scala - Auxiliary Constructor
- Scala - Primary Constructor
- Scala - This Keyword
- Scala - Nested Classes
- Scala - Getters and Setters
- Scala - Object Private Fields
- Scala - Singleton Object
- Scala - Companion Objects
- Scala - Creating Executable Programs
- Scala - Stateful Object
- Scala - Enumerations
- Scala - Polymorphism
- Scala - Access Modifiers
- Scala - Apply Method
- Scala - Update Methods
- Scala - UnapplySeq Method
- Scala - Inheritance
- Scala - Extending a Class
- Scala - Method Overloading
- Scala - Method Overriding
- Scala - Generic Classes
- Scala - Generic Functions
- Scala - Superclass Construction
- Scala Methods & Functions
- Scala - Functions
- Scala - Main Methods
- Scala - Functions Call-by-Name
- Scala - Functions with Named Arguments
- Scala - Function with Variable Arguments
- Scala - Recursion Functions
- Scala - Default Parameter Values
- Scala - Functions without Parameters
- Scala - Implicit Parameters
- Scala - Higher-Order Functions
- Scala - Nested Functions
- Scala - Extension Methods
- Scala - Anonymous Functions
- Partially Applied Functions
- Scala - Lazy Val
- Scala - Pure Function
- Scala - Currying Functions
- Scala - Control Abstractions
- Scala - Corecursion
- Scala - Unfold
- Scala - Tail Recursion
- Scala - Infinite Sequences
- Scala - Dynamic Invocation
- Scala - Lambda Expressions
- Scala Collections
- Scala - Collections
- Mutable and Immutable Collections
- Scala - Lists
- Scala - Sets
- Scala - Maps
- Scala - TreeMap
- Scala - SortedMap
- Scala - Tuples
- Scala - Iterators
- Scala - Options
- Scala - Infinite Streams
- Scala - Parallel Collections
- Scala - Algebraic Data Types
- Scala Pattern Matching
- Scala - Pattern Matching
- Scala - Type Patterns
- Scala - Exception Handling
- Scala - Extractors
- Scala - Regular Expressions
- Scala Files I/O
- Scala - Files I/O
- Scala Advanced Concepts
- Scala - Closures
- Scala - Futures
- Scala - Promises
- Scala - Traits
- Scala - Trait Mixins
- Scala - Layered Traits
- Scala - Trait Linearization
- Scala - Sealed Traits
- Scala - Transparent Traits
- Scala - Literal Type Arithmetic
- Scala - Inline keyword
- Scala - Def, Var & Val
- Scala - Dropped Features
- Scala - BDD Testing
Scala var vs. val Keywords
Scala is a programming language that mixes object-oriented and functional programming styles. It emphasizes using immutable values and functional programming principles. A big part of this is the use of the keywords var and val for declaring variables. You should understand the differences between var and val before writing Scala code. We will explain these two keywords in detail.
The var Keyword : Mutable Variables
The var keyword in Scala is used to declare mutable variables. A mutable variable is one whose value can be changed after it has been initialized. This is similar to variable declarations in many other programming languages like Java, Python, or C++.
Example
mutableVariable = 20 // This is valid println(mutableVariable) // Output: 20
When to Use var?
Although you can reassign variables using var. However, it is generally better to use immutable values (val) for several reasons −
- Predictability − Mutable variables can change unexpectedly. So, the code can be harder to understand and debug.
- Concurrency − In concurrent and parallel programming, immutable values are safer because mutable variables can cause race conditions and require complex synchronization.
- Functional Programming − Scala supports a functional programming style. The functions are pure and do not depend on and change external states.
The val Keyword: Immutable Variables
The val keyword declares immutable variables. Once you assign a value to a val, it cannot be changed. This is similar to constants in other languages. But with a subtle difference: a val can hold references to mutable objects, even though the reference itself cannot be reassigned.
Example
val immutableVariable = 10 // immutableVariable = 20 // This would cause a compile-time error println(immutableVariable) // Output: 10
When to use val?
There are various advantages to using val variables in Scala. These are −
- Security − The chance of unexpected side effects is low. So, the code can be more reliable.
- Clarity − There is more clarity due to the immutable property of val variables.
- Functional Programming − You need immutable data structure functional programming because of its essentiality. Therefore, secure concurrent operations can occur without the need for locks.
Example
val mutableList = scala.collection.mutable.ListBuffer(1, 2, 3) mutableList += 4 // The reference to mutableList is immutable, but the contents can change println(mutableList) // Output: ListBuffer(1, 2, 3, 4)
Performance Considerations
There can be performance differences between var and val data structures in Scala. The immutable data structures (i.e., val) can have slow performance because you need to copy data structures when changes are made. But there are advantages of immutability too. For example, it is safer and easier-to-maintain code which is usually more important than these drawbacks. We usually use val instead of val in Scala programs because the Scala style prefers immutability, so the code will be more predictable and robust.
Differences between var and val keywords in Scala
Feature | var | val |
---|---|---|
Mutability | It is mutable | It is immutable |
Reassignment | It can be reassigned | It cannot be reassigned |
Syntax |
var x = 10 |
val x = 10 |
Common Use Cases | When variable needs to change | When variable value should not change |
Functional Programming | Discouraged | Encouraged |
Concurrency | It has risk of race conditions | Thread-safe without synchronization |
Predictability | It is less predictable due to state changes | It is more predictable due to immutability |
Performance | It is potentially faster in certain cases | It may introduce overhead due to immutability |
Example Usage |
var counter = 0; counter += 1 |
val counter = 0 |
Side-effects | It can lead to side-effects | It minimizes side-effects |
Preferred in Scala | Rarely preferred | Preferred |