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:
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.
Difference Between var, val, and def Keywords 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. 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.
Table of Content
- var Keyword
- val Keyword
- def Keyword
- Difference between var, val and def Keywords
- Conclusion