Scala Variable Declaration

Scala variables are same as Java variables. Only syntax is slightly different.

Rules for Scala variable declaration
  • Type declaration and semicolon are optional.
  • Keyword var is used to declare the variables. Values can be reassigned.
  • Keyword val is used to define the values. Values cannot be reassigned (Same as Java’s final type)

//Variable Declaration : Mutable values
var strName = "BackToBazics" 
var isSemicolonOptional = true;
var iIntVar: Int = 2 
var iDoubleVar = 2.5
iDoubleVar = 3.5

//Value Declaration : Immutable values
val iIntVal = 2 
val iDoubleVal: Double = 2.5
//iDoubleVal = 3.5  - Not allowed in case of val

Scala also supports multiple variable assignments in a different way than Java. Here are the examples,

//Multi var Assignments
var (strName, iAge, dExperienceInYears) = ("John", 28, 3.5) 
strName = "Jolly" //Allowed 

//Multi var Assignments
val (strName, iAge, dExperienceInYears) = ("John", 28, 3.5) 
//strName = "Jolly" -- Not Allowed 

Next : Refer to Method Declaration in Scala

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>