
- 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
Difference Between var, val, and def Keywords
Keywords var, val, and def in Scala are used to declare and use variables, constants, and methods. The var is a variable that can change its value. So it is mutable and the value of a var can be reassigned. Whereas, val is used to declare constants. Once assigned, a val cannot change its value. So it is immutable. This is similar to final variables in Java where variable type remains constant. The def keyword is used to declare methods. Unlike var and val, which are evaluated when they are defined. The def is evaluated each time it is called. We have discussed these three keywords in this post.
Mutable Variables (var)
A variable declared with the keyword var is mutable meaning its value can change during the program's execution. This is useful when you need a variable that can be updated.
Syntax
The syntax of var variable is -
var myVar: String = "Foo"
Example
object Demo { def main(args: Array[String]) = { var myVar: Int = 10 println(myVar) myVar = 20 println(myVar) } }
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
Command
\>scalac Demo.scala \>scala Demo
Output
10 20
Here, myVar is a mutable variable of type Int. Its value is initially set to 10 and later changed to 20.
Immutable Variables (val)
A variable declared with the keyword val is immutable. So its value cannot be changed once assigned. This is similar to a constant.
Syntax
The syntax of the val variable is -
val myVal: String = "Foo"
Example
object Demo { def main(args: Array[String]) = { val myVal: String = "Hello, Scala!" println(myVal) // Uncommenting the next line will cause a compilation error // myVal = "New Value" } }
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
Command
\>scalac Demo.scala \>scala Demo
Output
Hello, Scala!
Here, myVal is immutable. Once set to "Hello, Scala!", it cannot be reassigned.
Methods (def)
Methods in Scala are declared using the def keyword. These represent functions and are evaluated each time they are called.
Syntax
The syntax to declare a method is -
def methodName(parameterList): ReturnType = { methodBody }
Example
object Demo { def add(x: Int, y: Int): Int = x + y def main(args: Array[String]) = { val result = add(3, 5) println(s"Result: $result") } }
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
Command
\>scalac Demo.scala \>scala Demo
Output
Result: 8
Here, we declared the add method using the def keyword. The add method takes two integers and returns their sum. It is evaluated each time it is called.
Lazy Values
Lazy values in Scala are defined using lazy val. Their initialization is deferred until these are accessed for the first time. These can be used for expensive computations.
Example
object Demo { lazy val lazyVal: Int = { println("Computing lazy value") 42 } def main(args: Array[String]) = { println("Before accessing lazyVal") println(lazyVal) println(lazyVal) } }
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
Command
\>scalac Demo.scala \>scala Demo
Output
Before accessing lazyVal Computing lazy value 42 42
Here, lazyVal is not computed until it is first accessed. So it is delaying the print statement inside its initialization block.
Variable Type Inference
When you assign an initial value to a variable, the Scala compiler can infer the type of the variable based on the value assigned. This is called variable type inference.
Syntax
The syntax of variable type inference is -
var myVar = 10 // myVar is inferred to be of type Int val myVal = "Hello, Scala!" // myVal is inferred to be of type String
Example
object Demo { def main(args: Array[String]) = { var myVar = 10 val myVal = "Hello, Scala!" println(myVar) println(myVal) } }
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
Command
\>scalac Demo.scala \>scala Demo
Output
10 Hello, Scala!
Here, myVar is inferred to be of type Int and myVal is inferred to be of type String.
Multiple Assignments
Scala supports multiple assignments. If a code block and method returns a tuple, the tuple can be assigned to a val variable.
Syntax
The syntax for using multiple assignments is -
val (myVar1: Int, myVar2: String) = (40, "Foo")
Example
object Demo { def main(args: Array[String]) = { val (myVar1, myVar2) = (40, "Foo") println(myVar1) println(myVar2) } }
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
Command
\>scalac Demo.scala \>scala Demo
Output
40 Foo
Here, myVar1 and myVar2 are assigned the values 40 and "Foo" respectively.
Differences Between def, var & val in Scala
The following table shows the key differences between def, var, and val keyword based on the various aspects −
Feature | var | val | def |
---|---|---|---|
Mutability | Mutable | Immutable | Not applicable |
Reassignment | Allowed | Not allowed | Not applicable |
Usage | Variables | Constants | Methods |
Syntax | var x: Type = value | val x: Type = value | def methodName(params): Type |
Evaluation Time | At declaration | At declaration | At each invocation |
Memory Allocation | At declaration | At declaration | At each invocation |
Lazy Evaluation | Not supported | Supported with lazy val | Not supported |
Example | var x = 10 | val y = 20 | def add(a: Int, b: Int) = a + b |
Similar to | Mutable variables in Java | Final variables in Java | Functions in Python |
Summary
- The var is used for mutable variables that can change value.
- The val is used for immutable variables that cannot change value.
- The def is used for defining methods that are evaluated each time they are called.
- The lazy val can be used for deferred initialization of values.
- So it provides an efficient way to handle expensive computations.