scala 随笔(6)apply 解析和构造类

首先说明apple的用法
当定义一个类,但是没有采用new 类时就是默认调用了apply 如:
   
   
  1. class ApplyTest(val name:String ) {
  2. println("right you are good :" + name)
  3. }
  4. object ApplyTest{
  5. def main(args: Array[String]): Unit = {
  6. val applyTest = new ApplyTest("Tom ");
  7. val applyTest2 = ApplyTest("Jim")
  8. }
  9. def apply(key: String): String = {
  10. println("come on :"+ key)
  11. "you are here"
  12. }
  13. }

apply 必须定义在object 对象里面。
如果没有new 则会自动调用apply 方法
输出结果如下:
right you are good :Tom 
come on :Jim

Process finished with exit code 0

比如 val x= List("d","v","a")
这个就是调用了Apply方法,List定义的源代码如下:
   
   
  1. override def apply[A](xs: A*): List[A] = xs.toList
因为List是一个抽象的,被sealed 定义的所以只有Apply这个唯一的通道。不能new 不能继承,不是实现。(参考 scala 随笔(5) sealed 解析)

回到最开始的问题,如果在new 对象的时候有异常怎么办。代码如下:
   
   
  1. class ApplyTest2 {
  2. class ApplyTest(val name:String ) {
  3. if(name.endsWith("jim")){
  4. throw new Exception("you should enter a name end with jim")
  5. }
  6. println("right you are good :" + name)
  7. }
  8. object ApplyTest{
  9. def main(args: Array[String]): Unit = {
  10. val applyTest = new ApplyTest("Tom ");
  11. val applyTest2 = ApplyTest("Jim")
  12. val x = List("A","b")
  13. }
  14. def apply(key: String): String = {
  15. println("come on :"+ key)
  16. "you are here"
  17. }
  18. }
  19. }

因为抛出一个异常,放入apple里面。然后可以进行一步动作。比如换种方式再new 一次

   
   
  1. class ApplyTest2(val name :String) {
  2. if(!name.endsWith("jim")){
  3. throw new Exception("you should enter a name end with jim")
  4. }
  5. println("right you are good :" + name)
  6. }
  7. object ApplyTest2{
  8. def main(args: Array[String]): Unit = {
  9. val applyTest2 = ApplyTest2("tom")
  10. }
  11. def apply(key: String) = {
  12. try{
  13. new ApplyTest2(key)
  14. }catch {
  15. case e: Exception
  16. => "you are wrong " + e.printStackTrace()
  17. case _:Any
  18. => "you are wrong too"
  19. }
  20. }
  21. }







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值