apply: 用括号传递变量(对象)1个或多个参数时,scala会把它转化为对apply方法的调用
val array=Array(1,2,3,4,5,6)
array(0), 取数组的第1个元素的操作会转换成 array.apply(0) 操作,这也能解释为何 Scala 数组取值不用中括号括下标的方式,由于它也是1次方法调用。
anyobject("key1")会被转换成 anyObject.apply("key") 操作,这也会让我们想到 Map 的取值操作
class SomeClass {
def apply(key:String):String ={
println("apply method called, key is: " + key)
"Hello World!"
}
}
val anyObject =new SomeClass
println(anyObject("key1"))
履行后输出结果是:
apply method called, key is: key1
Hello World!
说明是调用到了相应的 apply 方法的。
我们在构造 Array 或 Map 时,会简单的写成
val numNames =Array("zero","one","two")
上面的功效像是调用的 Array 类的 apply 工厂方法。一样看个单例对象的例子,也解释了伴生对象的 apply 方法的调用
object EMail {
def apply(user:String, domain:String):String ={
println("apply method called")
println(user + "@"+ domain)
}
}
val email =EMail("lyrebing","hotmail.com")
println(email)
伴生类与伴生对象中apply
class ApplyTest{
def apply()=println("I am into spark somuch!")
def haveATry{
println("Have a try on apply!")
}
}
object ApplyTest{
def apply()={
println("I am into scala somuch!")
new ApplyTest
}
}
object ApplyOperation{
def main(args:Array[String]){
val a=ApplyTest()
a.haveATry
//I am into scala somuch!
//Have a try on apply!
val b=new ApplyTest
b.haveATry
println(b()) //调用类的apply方法
//Have a try on apply!
//I am into spark somuch!
}
}