scala学习之apply

apply: 用括号传递变量(对象)一个或多个参数时,scala会把它转化为对apply方法的调用

val array=Array(1,2,3,4,5,6)
       array(0), 取数组的第一个元素的操作会转换成 array.apply(0) 操作,这也能解释为什么 Scala 数组取值不用中括号括下标的方式,因为它也是一次方法调用。
  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!
}

}










  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值