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)

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理