我的站点

一个系统软件工程师的随手涂鸦

Date: 九月 6, 2016

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)

Scala笔记(4)——main函数

scala中,main函数必须定义在object中(Java中,main函数必须是class中的static方法):

object Hello extends App{
  override def main(args: Array[String]): Unit = {
    ......
  }
}

或:

object Hello{
  def main(args: Array[String]): Unit = {
    ......
  }
}

其中应用程序的命令行参数通过Array[String]传给main()函数。

Powered by WordPress & Theme by Anders Norén