class ApplyTest{
def apply() = println("I am into Spark so much!!!")
def haveATry{
println("Have a try on apply!")
}
}
object ApplyTest{
def apply() = {
println("I am into Scala so much!!!")
new ApplyTest
}
}
object ApplyOperation {
def main(args: Array[String]) {
val array = Array(1,2,3,4,5)
val a = ApplyTest() //这里并没有new,然后确实返回了类的实例
a.haveATry
}
}
结果:
I am into Scala so much!!!
Have a try on apply!
在一个类的伴生对象里面,实现apply方法,在这里面可以创建类的实例。譬如val a = Array(1, 2, 3)就是使用了Array的apply方法。
同样,在class里面也可以使用apply方法:
object ApplyOperation {
def main(args: Array[String]) {
val a = new ApplyTest
a.haveATry
println(a()) //调用class的apply方法
}
}
结果:
Have a try on apply!
I am into Spark so much!!!
()
网友评论