Scala immutability

Immutable means you cannot change something. In Scala, all variables are immutable, unless specifically marked otherwise. This is the opposite to languages such as Java, where all variables are mutable unless specifically marked otherwise.

In Java, we can have the following function:

public void calculate(integer amount) { 
} 

We can modify the value of amount inside the calculate function. We can tell Java not to allow changing the value if we use the final keyword, as in:

public void calculate(final integer amount) { 
} 

Whereas in Scala:

def calculate (amount: Int): Int = {  
        amount = amount + 1; 
        return amount; 
} 
var balance = 100
val result = calculate(balance)

A similar routine leaves the value of the amount variable as it was before the routine was called:

We can see in the display that even though balance is a variable (marked as var), Scala will not allow you to change its value inside the function. The amount parameter to the calculate function is assumed to be a val and cannot be changed once initialized.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.104.29