Home

The apply and update methods

The apply and update methods

apply

When a is an object, and you write a(x), then the Scala compiler interprets this to mean a.apply(x). So by defining an apply method, you allow your object to be used in function notation. Here is an example:

class Linear(val a:Double, val b:Double) {
  def apply(x: Double): Double = a*x + b
}
This object can be used like a function:
scala> val c = new Linear(3, 5)
c: Linear = Linear@1eee7b7
scala> c(1.0)
res1: Double = 8.0
scala> c(2.0)
res2: Double = 11.0
Note that the line c(2.0) has exactly the same meaning as c.apply(2.0).

Perhaps you have wondered why we can create arrays by simply saying

val A = Array(1, 2, 3)
Shouldn't there be a new keyword? The reason is that the Array class has a companion object, and this companion object defines an apply method. So Array(1,2,3) really means Array.apply(1, 2, 3), and this method creates an array of integers using new Array[Int](3), and places the numbers 1, 2, and 3 in the new array.

update

Similarly, when you write a(x) = y, the compiler interprets this to mean the same as a.update(x, y). This can be used to implement mutable container objects with a syntax similar to arrays, such as maps.