In Scala, strings are immutable, which means that they cannot be altered once created.
For example, the following code:
var message = "Jello world"
message[0] = 'H'
would produce an error.
Variable can still be changed:
Note that this does not mean that message cannot be changed, just that the individual characters of a string literal cannot be changed.
"Jello world" is a string literal that Scala stores in memory, while message is a variable that refers to that string literal.
When we do message[0] = 'H', we are trying to alter the string literal "Jello world", which is not allowed.
But like any other variable, message can be changed by reassigning it with a new string, like this:
var message = "Jello world"
message = "Hello world"
println(message)
This code would output:
Hello world
Instead of trying to alter the first string, this code now creates a new one ("Hello world"), stores it in memory and tells message to refer to this new string.
Assignment
Follow the Coding Tutorial and let's practice with string immutability!
Hint
Look at the examples above if you get stuck.
Free plan: 30 tutor messages. Premium is unlimited.