The Scala apply Method
Scala apply method
The apply
method is called in expression of the form Object(arg1,...,argN)
[1].
We have seen that we can write both experssions
val arr1 = new Array[Int](10)
val arr2 = 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))
Not having the new
keyword is handy for nested expressions, like the one below
val arr3 = 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)
}
val cls = MyCls(1, 20)
println(cls.idx)
println(cls.value)
- Cay Horstmann,
Scala for the Impatient 1st Edition