Scala Variables

    Variables

    Scala has two types of variables.

    1. Immutable: These are the type of variables which cannot be changed after 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 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, 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:

    Scala variables

    Naming convention of variable in Scala

    • Variable name should be in lower case.
    • Variable name can contain letter, digit and two special characters(Underscore(_) and Dollar($) sign)
    • Variable name must not contain the keyword or reserved word.
    • Starting letter of the variable name should be an alphabet.
    • White space is not allowed in variable name.