Difference Between var, val, and def Keywords in Scala
Last Updated :
05 Apr, 2024
Scala is a general-purpose, high-level, multi-paradigm programming language. It is a pure object-oriented programming language that also provides support to the functional programming approach. Scala programs can convert to bytecodes and can run on the JVM (Java Virtual Machine). Scala stands for Scalable language. It also provides Javascript runtimes. Scala is highly influenced by Java and some other programming languages like Lisp, Haskell, Pizza, etc. This article focuses on discussing the differences between var, val, and def keywords in Scala.
var Keyword
'var' is used to declare mutable variables. Once it is defined, the value of a variable declared with 'var' can be reassigned.
Syntax:
var variableName: DataType = value
Example:
Scala
object Main {
def main(args: Array[String]): Unit = {
var age: Int = 25
println(age)
// Reassignment allowed
age = 30
println(age)
}
Output:
After running above it initializes age with the value 25, prints it, then reassigns age to 30 and prints it again. So, the output will be 25 followed by 30.
var-keyword-outputval Keyword
Scala's 'val' is similar to a final variable in Java or constants in other languages. It's also worth remembering that the variable type cannot change in Scala.
'val' is used to declare immutable variables. Once it is defined, the value of a variable declared with 'val' cannot be changed.
Syntax:
val variableName: DataType = value
Example:
Scala
object Main {
def main(args: Array[String]): Unit = {
val name: String = "Alice"
println(name)
// name = "Bob" // Error: Reassignment to val is not allowed
}
}
Output:
It declares a val named name with the value "Alice", prints it, and demonstrates that reassignment to val is not allowed by commenting out the reassignment line. When you run this code, it will print Alice as the output.
val-keyword-outputdef Keyword
'def' keyword is used to define methods (functions). Methods defined with 'def' are evaluated each time they are called.
Syntax:
def methodName(parameterList): ReturnType = { methodBody }Note
Example:
C++
object Main {
def add(x: Int, y: Int): Int = {
x + y
}
def main(args: Array[String]): Unit = {
val result = add(3, 5)
println("Result: " + result) // Output: Result: 8
}
}
Output:
The above code defines a method add(x: Int, y: Int): Int that returns the sum of two integers, wrapped within an object Main with a main method for execution. When run, it calculates add(3, 5) and prints the result.
def-keyword-outputNote:
Unlike 'val' and 'var' , 'def' is used for defining functions rather than variables. Also, unlike 'val' and 'var', 'def' doesn't store a value but rather defines an action to be performed.
Difference between var, val and def Keywords
Features
| 'var' Keyword
| 'val' Keyword
| 'def' Keyword
|
---|
Mutability
| Mutable
| Immutable
| Not Applicable
|
---|
Reassignment
| Allowed
| Not Allowed
| Not Applicable
|
---|
Usage
| For declaring
variables
| For declaring
constants
| For declaring
methods
|
---|
Syntax
| var name: Type = value
| val name: Type = value
| def methodName(params): ReturnType = { body }
|
---|
Memory Allocation
| Allocated at declaration
| Allocated at declaration
| Allocated at invocation
|
---|
Performance
| May incur overhead
| Minimal overhead
| May incur overhead
|
---|
Execution Time
| At each assignment
| Once at declaration
| At each invocation
|
---|
Lazy Evaluation
| Not supported
| Not supported
| Supported with lazy 'val'
|
---|
Example
| var x: Int = 5
| val y: String = "Hello"
| def add(x: Int, y: Int): Int = { x + y }
|
---|
Conclusion
In short, the 'val 'and 'var' are evaluated when defined, while 'def' is evaluated on call. Also, 'val' defines a constant, a fixed value that cannot be modified once declared and assigned while 'var' defines a variable, which can be modified or reassigned.
Similar Reads
Difference between a Seq and a List in Scala
Sequences of items are represented in Scala using two different collection types: Seq and List. Nonetheless, there are significant distinctions between them in terms of use, implementation, and mutability. Mutability:Seq: Sequences of items, known as seqs, may be either changeable or immutable. It i
2 min read
Difference Between Haskell and Scala
Haskell is a general-purpose programming language that is normalized and has unadulterated practical programming features. It was developed and structured by Lennart Augustsson, John Hughes, Paul Hudak, John Launchbury, Simon Peyton Jones, Philip Wadler, and Erik Meijer. Its composing discipline is
4 min read
Difference Between Groovy and Scala
Groovy : Groovy is an object-oriented high-level programming language that is Java syntax compatible. It is used as both programming language and scripting language for the Java Platform. In the year 2004, Groovy language was developed by Bob McWhirter and James Strachan. The source code of Groovy i
3 min read
Difference between Normal def defined function and Lambda
In this article, we will discuss the difference between normal 'def' defined function and 'lambda' function in Python.Def keywordâââââââIn Python, functions defined using def keyword are commonly used due to their simplicity. Unlike lambda functions, which always return a value, def functions do not
2 min read
Difference between Case Objects vs Enumerations in Scala
Scala offers multiple constructs for representing a fixed set of values, among which case objects and enumerations stand out. While both serve similar purposes, they have distinct characteristics and use cases. In this article, we'll explore the differences between case objects and enumerations in S
4 min read
How to Reverse keys and values in Scala Map
In Scala, Map is same as dictionary which holds key:value pairs. In this article, we will learn how to reverse the keys and values in given Map in Scala. After reversing the pairs, keys will become values and values will become keys. We can reverse the keys and values of a map with a Scala for-compr
2 min read
Scala - Expression that Can't be Reduced to a Value
Scala adheres to expression-centric philosophy design, where anything can be evaluated to produce value. This is a way to be more expressive and follow the principles of functional programming. Substitution Model in ScalaThe substitution model is a fundamental concept in programming. It provides a w
2 min read
Throw Keyword in Scala
The throw keyword in Scala is used to explicitly throw an exception from a method or any block of code.In scala, throw keyword is used to throw exception explicitly and catch it. It can also be used to throw custom exceptions. Exception handling in java and scala are very similar. Except that scala
3 min read
Reassignment of val in Scala
Scala is a general-purpose, high-level, multi-paradigm programming language. It is a pure object-oriented programming language that also provides support to the functional programming approach. In Scala, there are two ways of declaring variables. Using varUsing ValUsing var! as in VariableIt allows
2 min read
Getters and Setters in Scala
Getter and Setter in Scala are methods that helps us to get the value of variables and instantiate variables of class/trait respectively. Scala generates a class for the JVM with a private variable field and getter and setter methods. In Scala, the getters and setters are not named getXxx and setXxx
4 min read