val 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:
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.
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