Other answers relate to your specific case. However, you asked about the general case, so I will try to answer from this point of view.
Firstly, def used to determine the method of a non- function (it is better to know this difference now). But, you are right, index is the name of this method.
Now, unlike other languages โโthat may be familiar with (for example, C, Java), Scala allows you to define methods with an expression (as suggested by the syntax of the assignment operator, = ). That is, everything after = is an expression that will be evaluated to a value each time the method is called.
So, while in Java you should say:
public int three() { return 3; }
In Scala, you can simply say:
def three = 3
Of course, the expression is usually more complex (as in your case). It may be a block of code, for example, you are more used to seeing, in which case this value has the meaning of the last expression in the block:
def three = { val a = 1 val b = 2 a + b }
Or it may include a method call for another object:
def three = Numbers.add(1, 2)
The latter, in fact, is exactly what happens in your particular example, although this requires a bit more explanation. The game involves two parts of magic:
- If the object has an
apply method, then you can treat the object as if it were a function. You can say, for example, Add(1, 2) when you really mean Add.apply(1,2) (assuming the Add object with the apply method, of course). And in order to be understandable, it should not be an object defined using the keyword object . Any object with a suitable apply method will do. - If the method has one by-name parameter (for example,
def ifWaterBoiling(fn: => Tea) ), you can call a method like ifWaterBoiling { makeTea } . The code in this block is evaluated lazily (and may not be evaluated at all). This would be equivalent to writing ifWaterBoiling({ makeTea }) . The { makeTea } simply defines the expression that is passed, not evaluated, for the fn parameter.