Search⌘ K
AI Features

Solution Review: Declaring a Variable

Learn to declare immutable variables in Scala by using the val keyword with explicit type annotations, assign values, and print the variable's content. This lesson helps you master variable declaration basics, type specification, and output commands essential for Scala programming.

We'll cover the following...

Task

In this challenge, you needed to declare an immutable variable of type Int and initially assign it a value of 100. You then needed to print myFirstVariable.

Solution

Let’s look at each component separately:

  • Immutable Variable - When declaring a variable, we first need to specify if it is immutable or mutable. An immutable variable is declared using the val keyword.

  • Variable Name - After specifying the type of variable, we need to give the variable a name. In our case, the name of the variable is myFirstVariable.

  • Data Type - After giving the variable an identifier, we need to specify its data type which is done using :. In our case, we needed a variable of type Int hence, we would need to write :Int.

  • Assigning a Value - For assigning an initial value to the variable, we insert a = after the data type, followed by the desired value to be assigned. In our case, that value was 100.

val myFirstVariable: Int = 100
  • Finally, use either the print or println method to print myFirstVariable.
print(myFirstVariable)

or

println(myFirstVariable)

You can find the complete solution below:

Scala
val myFirstVariable: Int = 100
print(myFirstVariable)

In the next lesson, we will learn about type casting.