Overview

The apply method is called in expression of the form Object(arg1,...,argN) [1].

The apply method

We have seen that we can write both experssions

val arr1 = new Array[Int](10)
arr1: Array[Int] = Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
val arr2 = Array(10)
arr2: Array[Int] = Array(10)

The first expression creates an Array of length 10. In this expression the constructor is called. In contrast, in the second expression, the apply method is called. And an Array instance is created having length one and value

println(arr2(0))
10

Not having the new keyword is handy for nested expressions, like the one below

val arr3 = Array(Array(1, 7), Array(2, 9))
arr3: Array[Array[Int]] = Array(Array(1, 7), Array(2, 9))

In order to be able to use expressions like the above, the apply method must be defined [1]. We can do this as shown below [1]

class MyCls (val idx: Int, val value: Double){
    
}

object MyCls{
    def apply(idx: Int, value: Double) = new MyCls(idx, value)
}
defined class MyCls
defined object MyCls
val cls = MyCls(1, 20)
cls: MyCls = ammonite.$sess.cmd5$Helper$MyCls@5e0ad6c6
println(cls.idx)
println(cls.value)
1
20.0

References

  1. Cay Horstmann, Scala for the Impatient 1st Edition