Skip to main content
HomeTutorialsScala

Variables in Scala

Learn about Scala's variables, rules for defining variables, different types of variables with multiple declaration and assignments along with the scope of a variable.
Oct 22, 2019  · 10 min read

Check out DataCamp's recently launched Scala course: Introduction to Scala.

Scala is widely used by data scientists when dealing with the large volumes of the data used with the Apache Spark together in the field of Big Data. It is both object-oriented and functional programming language with many other essential features listed below:

  1. Scala is known to be a statically typed language, where the data type for the variable is defined before it is used. The type checking is done at compile-time rather than at the run time.
  2. It is also a "Strongly Typed" language where the variables are checked before having an operation in it.
  3. It also supports Type Inference, where the compiler infers the type from the expression or literals, so declaring the type of variable is optional.

In this tutorial, you are going to cover the following topics:

Variables

Variables are the named space in memory, and the compiler allocates reserved location according to the data type of the corresponding variable. The variable is declared with the following syntax in Scala as follows:

val or val variable_name: variable_datatype = value;

In the above syntax, the variable can be defined in one of two ways by using either the 'var' or 'val' keyword. It consists of 'variable_name' as your new variable, followed by a colon. The data type of variable is 'variable_datatype.' which can be any valid data type. After that 'value', the symbol gets assigned to 'variable_name.'

For example:

val varValue: Byte = 8;

The 'val' is the keyword for defining the variable, and 'varValue' is the variable name. It is of the data type 'Byte' and contains the value 8. 'Byte' is an 8-bit signed value, which ranges from 2−7 to 27−1.

The 'variable_datatype' above can be of any data type which exists in Scala and are as follows.

  1. Int: Is a 32 bit signed (positive or negative value), which has a range from 2−31 to 231−1.
  2. Byte: It is an 8-bit signed value which has a range from 2−7 to 27−1.
  3. Short: It is 16-bit signed value has a range from 2−15 to 215−1.
  4. Float: It can be either 32 bit or 64 bit.

Similarly, other data types like Long, Char, Boolean, Char, String, Boolean, Null consists of their own range, and a detailed explanation is given in the Beginner’s Guide to Scala tutorial. Also, the 'variable_datatype' should start with a capital letter, i.e., Int contains 'I', which indicates all of the data types above are the objects in Scala.

Rules Defining Variable in Scala

The rules and convention for defining the variables in Scala are as follows:

  1. The variable name starts with a lower camel case. For example, in the variable name 'nameOfGirl,' contains 'n' as the small alphabet. Afterward, capitalize all the beginning alphabet of the word like 'O' and 'G.'
  2. The variable name should not contain the reserved word or keyword defined in Scala.
  3. The variable name can contain dollar sign ('$') and the underscore ('_') sign. However, other special characters such as '#','&', etc., are not allowed. Also, using underscore is discouraged.
  4. White space (tabs, space) is not allowed in a variable name.
  5. The variable name must start with a letter and cannot begin with a number or other characters.

Mutable Variables

Mutable variables allow changing the values of variables even after the declaration of variables.

The syntax of Mutable variable is shown below:

var variable_name : variable_datatype = value;

The syntax of Mutable variable can also be defined as follow:

var variable_name = value;

The example of Mutable variable is shown below:

var nameOfThing: String = "Car";

The above example contains var as a keyword, which is for defining Mutable Variables. The name of the variable is 'nameOfThing'. A colon follows it with the data type of variable as 'String'. Its value stored in the memory will be 'Car'.

The above example of Mutable variable with the different syntax can be done as below:

var nameOfThing = "Car";

You can define your variable without the data type of the variable, as done above. The Scala compiler automatically determines it to be a 'String' data type, which is called Type Inference.

You can easily change the value of the variable as done below:

nameOfThing = "Bike";
print(nameOfThing)

The value of the variable will change from "Car" to "Bike." The output will be "Bike," because the 'var' keyword lets you change the value of the variable (Source: Variables in Scala).

Immutable Variables

Immutable variables are that variable which value cannot be changed once it is created and is declared using 'val' keyword.

The syntax of the Immutable Variable is shown below:

val variable_name : variable_data type = value;

The syntax of the Immutable variable can also be defined as follow:

val variable_name = value;

The example of the Immutable variable is shown below:

val numberOfThing: Int = 2;

The above example contains val as a keyword for defining Immutable variables and the name of a variable as 'numberOfThing.' It is followed by a colon with the data type of the variable as 'Int' along with value stored in memory is 2.

The above example of Immutable variable with the different syntax can be done as below:

val numberOfThing = 2;

You can define your variable without the data type of the variable as done above, where the Scala compiler automatically figures it to be an 'Int' data type. The process is called Type Inference (Source: Variables in Scala).

You cannot change the value of the variable as done below:

numberOfThing = 7;

The above example will result in an error like "error: not found: value numberOfThing", which shows that the reassignment of value is not possible as shown below :

error

Multiple Declarations and Assignments

Multiple declarations can be possible in Scala using the 'var' keyword with the variable name separated by commas and the "=" sign with the value for the variable.

var (x, y, z) = (5, 4.5, "Sit")

In the above example, you can see all of the variables x,y, and z get assigned to value 5,4.5 and "Sit" correspondingly as follows.

variables

The multiple assignments can be possible in Scala in one line by using 'val' keyword with variable name separated by commas and the "=" sign with the value for the variable.

val a, b, c = 1;

In the above example, you can see all of the variables a,b, and c get assigned to value 1 as follows.

variables

Scope of a Variable

The scope is the visibility of the variables which have its life-time inside the specified blocks of the code. The variable can be defined in either Local or Global Scope. For example:

var globalVar = 10
def sub(){
var difference = 9-4;
}
print(difference)//Error
print(globalVar)//Valid

In the above code, the 'difference' variable is in Local Scope where it is declared inside the 'sub' method, and subtraction operation will give valid results, but printing value outside the method 'sub' will cause an error. There is also a Global Scope where variable 'globalVar' can be accessed anywhere in the program, and any operation can be performed to it.

There are three types of scope for variables in Scala (Source: Scala- Variables):

  1. Local variables
  2. Fields
  3. Method Parameters

Local Variables

Local variables are mutable or immutable variables that are declared inside a method and can only be accessible inside methods but not outside it.

You can see the simple example below to know about Local variables:

class Perimeter  
{
    def triangle()  
    {
        var side1 = 10;
        var side2 = 20;
        var side3 = 30;

        var total = side1+side2+side3;
        print("Perimeter of the  triangle is: " + total);
    }
}

object Test  
{

    def main(args:Array[String])  
    {
        val p1 = new Perimeter()
        p1.triangle()
    }
}
defined class Perimeter
defined object Test

The above code gives the result:

The perimeter of the triangle is: 60

The program above contains a class called 'Perimeter' and object to be 'Test' where there is a method called as a triangle having three mutable variables as side1, side2, side3. The calculation and the printing of the result will be done inside the method, which will give the correct output.

Fields

Those variables defined inside the class are known to be as field variables which can be of any type either mutable or immutable variables. The access modifier will be automatically public if the variable is declared inside the class but should not be defined inside any method where the variable is accessible to anywhere in the program. However, a private variable can be accessed inside the defined class but cannot be accessed outside the scope of the class or even in the object too.

class FieldExample
{
  var value1 = 10;
  private var value2 = 30;
  def operation()
  {
    println("Value of value1:"+value1)
  }
  println("Value of value2: "+value2);
}

object Demo
{
  def Main(args:Array[String])
  {
    val obj = new FieldExample()
    obj.operation()
    print(obj.value1)//Valid
    print(obj.value2)


  }
}
defined class FieldExample
defined object Demo

The above code gives the result:

Value of value2: 30
Value of value1:10
10

The program above contains a class called 'FieldExample,' object to be 'Demo' and a method as 'operation.' The public variable value1 can be accessed using dot notation, and the value is printed as 10. The private variable as value2 to be 30 where accessing that variable and printing will cause an error.

Method Parameters

The method parameters are the variables that accept the value when the method is being called, and the variable must be mutable, which is defined using 'val' keyword. Also, the variable can be accessed outside the method when there is a reference made to it.

You can see the simple example below to know about Method Parameters:

class Triangle
{
    def calculate(height: Int, width: Int)
    {
        var result = 0.5*(height+width);
        println("Area of triangle is: " + result);
    }
}

object Area  
{
     def main(args:Array[String])
    {
        val a = new Triangle()
        a.calculate(4,5);
    }
}
defined class Triangle
defined object Area

The above code gives the result:

Area of triangle is: 4.5

The program above contains a class called 'Triangle.' It includes a method called 'calculate' with two method parameters height and width. The integer value 4 and 5 get passed when 'calculate' is called using object instance a.

Conclusion

Congratulations, you have made it to the end of this tutorial!

In this tutorial, you have covered about Scala's variables, Rules for defining variables, different types of variables with Multiple Declaration and Assignments along with Scope of variable in it.

If you would like to learn more about Scala, take DataCamp's Introduction to Scala course.

Topics

Courses for Python

Course

Introduction to Scala

3 hr
23.6K
Begin your journey with Scala, a popular language for scalable applications and data engineering infrastructure.
See DetailsRight Arrow
Start Course
See MoreRight Arrow
Related

tutorial

Operators in Scala

Learn about the different operators used in the Scala programming language.

Aditya Sharma

6 min

tutorial

Beginner’s Guide to Scala

Learn the basics in Scala including syntax, how to set up an environment, and various common data types.
Aditya Sharma's photo

Aditya Sharma

6 min

tutorial

Basics of Functions and Methods in Scala

Learn about the basics of methods, named arguments, default parameter values, variable arguments in addition to different kinds of functions.

Olivia Smith

10 min

tutorial

Lists in Scala

Learn what lists are and how they can be leveraged in the Scala Programming Language.
Aditya Sharma's photo

Aditya Sharma

6 min

tutorial

Scala Classes and Objects

In this tutorial, you will learn about the fundamental notions of object-oriented programming in Scala: Classes and Objects.
Aditya Sharma's photo

Aditya Sharma

8 min

tutorial

Scala Traits

Learn about the use of traits in Scala with the help of syntactic examples.
Aditya Sharma's photo

Aditya Sharma

6 min

See MoreSee More