Scala笔记(5)——apply method

本文选自Deeper Look at the Apply Method in Scala

In Scala, there is a language feature generally referred to as “The Apply Method” that has the following rules:

Any object that has an apply method can be called with the .apply omitted.
Functions are no more than objects.

Let’s take a look at an example. Given the following abbreviated definition of class Array, and an instance a,

class Array{
def apply(index:Int) = { …some code to get from the array… }
}

val a = new Array(whatever)

Then the following calls are essentially equivalent:

a.apply(7)
a(7)

发表评论

电子邮件地址不会被公开。 必填项已用*标注