This is a short Scala post to explain what the difference is between val and var. I was showing some Scala code to a co-worker this past week and he was asking what the difference was between val and var. It is quite simple:
val defines a fixed value, it is a read only variable
var defines a mutable variable, this variable can be modified
In Java you would use final to create a variable which would be read only, this is the same as val in Scala.
Let’s look at some very simple Scala code.
object Test {
def main(args: Array[String]) = println("done with main")
var Test1 =5
println("Test1 " + Test1)
Test1 = 6
println("Test1 " + Test1)
}
Running the code above will give the following output
Test1 5
Test1 6
done with main
If you are trying to use val, you will get an error, change var to val and see if you can compile the code
object Test {
def main(args: Array[String]) = println("done with main")
val Test1 =5
println("Test1 " + Test1)
Test1 = 6
println("Test1 " + Test1)
}
Here is the error, the code won’t even compile
Description Resource Path Location Type reassignment to val Test.scala /ScalaTemp/src line 8 Scala Problem
So as you can see, val is read only, while with var you can modify the variable.
If you want to play around with Scala, take a look at Installing Scala 2.10 on Eclipse Juno

Denis has been working with SQL Server since version 6.5. Although he worked as an ASP/JSP/ColdFusion developer before the dot com bust, he has been working exclusively as a database developer/architect since 2002. In addition to English, Denis is also fluent in Croatian and Dutch, but he can curse in many other languages and dialects (just ask the SQL optimizer) He lives in Princeton, NJ with his wife and three kids.