Start learning free

LESSON 12 OF 348 · VARIABLES

Variable Reassignment in Scala in Scala

Lesson

You can always change the value stored in a variable with the assignment operator(=):

// Initializing with 5:
var myVar = 5

// Assigning the value 10:
myVar = 10

println(myVar) // Output: 10

First, this code creates a variable named myVar and initializes it with 5.

Then, the code assigns 10 to myVar. Now, when myVar appears again in the code, the program will treat it as if it is 10.


Assigning the Value of One Variable to Another:

You can also assign the value of some variable to another variable using the assignment operator:

var myVar = 5
var myNum = 10

myVar = myNum

println(myVar) // Output: 10

First, this code creates a variable named myVar and initializes it with 5 and another variable named myNum and initializes it with 10.

Then, the contents of myNum (which is 10) is assigned to the variable myVar. Now, myVar also has the value of 10.


Assignment
Follow the Coding Tutorial and let's reassign some variables.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 1
    Ctrl + Enter to check

    Variable Reassignment in Scala

    Keep going with ScalaAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free