Scala Tutorials Part #17 - The Update method
Originally Posted On : 14 Jun 2017
The Update method
This is part 17 of the scala tutorial series. Check here for the full series.
update method is a companion to the
apply method which is used to update a value of an existing type in an object. It’s usage in core language
libraries is pretty widespread as the apply method itself.
Apply and Update methods are normal functions to the user, but the compiler treats them in a special way.
Arrays unlike java are part of collections in scala. Let’s consider the below example to understand how
update method works.
First thing to understand is that we can put any kind of logic inside the apply and update methods. But best practices advise developers to stick
to certain standards.
apply is generally used for applying a value(constructor in this case) and
update is used to update the array value
at a particular index. Since we are mutating the array object itself, it is generally recommended to use update method only in the case of mutable
Notice that array elements are called using the
() symbols instead of the
 as in java. This is again because array is a class and not
something native as in java.
The Array class does not have a fully formed definition of the update method because it gets generated at compile time. This will be more clear while writing our own example below.
Let’s imagine that we have a class in which we need to store list of user names. We define the class skeleton as follows.
We will see in detail what the
Map data structure is in later tutorials. For now, it can be assumed it is the equivalent of a java hash map.
Next we will define an apply method which will return the element with that key.
Now we are ready to define our update method which updates/adds a value for the given key.
This adds/updates the existing key-value pair inside of the map named
list. Below is an example of how to consume this.
Let’s create an additional
update method for deeper understanding. This is slightly more complicated to visualize so we will add a
helper method in our class to print out the list.
Next comes our update method,
The logic is pretty simple. It searches for a name which matches with the given one, then it replaces with the replacement string.
If this approach is followed across the code base then it can lead to a much cleaner abstraction instead of having methods for each of these operations. Since this is a powerful tool, we have to keep in mind that with power comes responsibility.
Among the scala community, methods such as
update are often referred to as magic methods, in the sense that their true power
is not visible outside.
All these lead to functional programming, but let’s not go there yet. A bottom up approach of learning the smaller things and then trying to understand the bigger picture works really well.