Introduction and Lesson Overview

Welcome! Today, we're delving into Scala variables, critical elements in any programming language. They serve as containers that store and handle data. In this lesson, we'll explore what they are, learn about assigning values, naming them, and discuss the nature of constants in Scala.

What are Variables in Scala?

A variable is a slot in memory that holds data; its content can change during a program's execution. For example, in the snippet below, the value "Alice" held by myName is replaced by "Bob":

@main def run: Unit = 
  var myName = "Alice"
  println(myName) // Output: Alice

  myName = "Bob"
  println(myName) // Output: Bob

Scala features two types of variables - val, which is immutable (cannot be changed once assigned), and var, which is mutable (can be changed after its initial assignment).

Declaring Variables in Scala

As was mentioned earlier, in Scala, you can reassign values to variables declared with var. However, variables declared with val are immutable. Let's assign and reassign a value to myAge to see this action:

@main def run: Unit = 
  var myAge = 25
  println(myAge) // Outputs: 25

  myAge = 30
  println(myAge) // Outputs: 30

Now, let's attempt to alter a constant, myBirthYear:

@main def run: Unit = 
  val myBirthYear = 1991
  println(myBirthYear) // Outputs: 1991

  myBirthYear = 1990  // Error: Val cannot be reassigned
Scala Variable Naming Conventions

In Scala, we adhere to the camelCase naming convention. CamelCase involves writing compound words or phrases such that each word or abbreviation begins with a capital letter, except for the first word. This practice helps in providing clear, purposeful names. Good examples include numberOfStudents, accountBalance, userDetails. Poor examples like c, xyz, temp lack a clear purpose and should therefore be avoided.

Understanding Constants in Scala

In Scala, val is used for declaring constants as shown below:

@main def run: Unit = 
  val pi = 3.14159
  println(pi) // Outputs: 3.14159

  pi = 3.15  // Error: Val cannot be reassigned

Constants are useful for representing values that are not meant to change.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal