Variables
Scala has two types of variables.
1. Immutable: These are the type of variables that cannot be changed after the first assignment. Such variables are created using ‘val’ keyword.
val blogName: String = “GettingStartedWithScala”
2. Mutable Variable: These are the variables whose values can change. Such variables are created using ‘var’ keyword. Scala discourages the usage of mutable variables. They should be avoided unless no other construct is possible as a replacement.
var counter: Int = 10
Another good feature that you get in Scala is, that the Scala compiler is smart enough to understand the type of variable based on the value that is assigned to it. This feature is known as type inference.
Syntax
val VariableName : DataType = [Initial Value]
or
var VariableName : DataType = [Initial Value]
Example:
The naming convention of variables in Scala:
- The variable name should be in lowercase.
- A variable name can contain a letter, digit, and two special characters(Underscore(_) and Dollar($) sign)
- Variable names must not contain the keyword or reserved word.
- Starting letter of the variable name should be an alphabet.
- White space is not allowed in a variable name.