×

Scala Tutorial

Scala Basics

Scala Control statements

Scala Functions

Scala Arrays

Scala Lists

Scala Misc. Topics

Scala Practice

Scala val Keyword

By IncludeHelp Last updated : October 09, 2024

The 'val' Keyword

Scala's val keyword is used to define a constant or controlled variable in the program. You can skip the declaration of data type in Scala while using val keyword. The variables declared using val keyword are immutable variables.

Immutable Variables are those variables whose value can not be changed in the program. These variable have a fixed value that remains constant throughout the program. Any attempt to change the value causes an error. Example of immutable variables, names, id, etc that are fixed. Usually, we tend to fix strings immutable so that important contained cannot be changed.

Syntax to declare immutable variables using val keyword

val I = 102;
val H : string = "IncludeHelp";

Syntax Explanation

The val keyword is used to initialize the variables. The first initialization is of an int data type which is not declared explicitly, the compiler will take it based on its value. In the second initialization, the data type is explicitly given. This means that irrespective of the value the data type will be a string.

val keyword can define constant variables of all data type. You can not change the value of this variable. Once the value is initialized it is the final value.

Scala example of the val keyword

object MyClass {
  def main(args: Array[String]): Unit = {
    // Variable Initialized with value52
    val myVar = 52;
    val name: String = "IncludeHelp"

    print("Value of my myVar = " + myVar + "\n")
    print("Hello this is " + name)
  }
}

Output

Value of my myVar = 52
Hello this is IncludeHelp

Example Explanation

The val keyword here initializes two variables. myVar with value 52 which will itself be initialized as an integer. Another one is name defined as a string.

What if you change the value of val variable. In this code, we have changed the value of myVar.

Example 2

object MyClass {
  def main(args: Array[String]): Unit = {
    // Variable Initialized with value52
    val myVar = 52;
    val name: String = "IncludeHelp"

    print("Value of my myVar = " + myVar + "\n")
    print("Hello this is " + name)
    myVar = 23;
    print("Value of my myVar = " + myVar + "\n")
  }
}

Output

ValKeyword.scala:12: error: reassignment to val
		myVar = 23;
                      ^
one error found
cat: /release: No such file or directory

Example Explanation

Changing the value of val variable is an error. The compiler outputs an error "reassignment of val" if you by mistake change its value.

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.