2

I understand that I can write

myArray(index) = newValue

to update an array. However, I don't understand how this works internally. I learned from another question here that = is usually not a method call in Scala. I also understand that the brackets are shorthand for calling the apply() method on an object, so I assume myArray(index) means myArray.apply(index).

But how does it work to assign a value to something that has just been returned from a method call?

1 Answer 1

3

You are correct that

myArray(index)

is syntactic sugar for

myArray.apply(index)

However, adding an assignment with the = operator completely changes the meaning:

myArray(index) = newValue

is a special syntax for the update method:

myArray.update(index, newValue)

This does not only apply for Arrays; you can make use of it on your own. In fact, many classes in the Scala Collections Framework make use of this syntactic sugar. For example, the scala.collection.mutable.Map#update(A,B) can also do this.

class MyClass(var i: Int)
{
    def update(i: Int, j: Int) = { this.i = i + j }
}

var my = new MyClass(1)
my(1) = 2
println(my.i) // prints 3
Sign up to request clarification or add additional context in comments.

4 Comments

Does this work for all classes? Does it mean there is a general rule, or is it only working for arrays? If it is special, how can I specify something similar for my own classes?
Edited my answer to address you comment.
@lex82: As a general rule, Scala works very hard to have only general rules ;-) Contrary to popular belief, Scala is a pretty simple language, simpler than Java, for example, precisely because it tries to have only a few powerful general rules and no special cases, corner cases, boundary cases, special built-in magic syntax, etc.
Heres the relevant section of the SLS. It explains quite nicely how the expressions are expanded: scala-lang.org/files/archive/spec/2.11/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.