伴生类和伴生对象(apply方法的实践)

具有相同名字的object和class,分别为伴生对象和伴生类

1 class ApplyTest { //伴生类
2   
3 }
4 
5 object ApplyTest { //伴生对象
6   
7 }

补充代码:

object ApplyApp {
  def main(args: Array[String]): Unit = {
    var c = ApplyTest() // ==>object.apply()
    c()         //==>class.apply()
  }
}
/**
  * 伴生类和伴生对象:具有相同名字的object(伴生对象)和class(伴生类)
  */
class ApplyTest {
  def apply() = {
    println("this is the apply method in class")
  }
}

object ApplyTest {
  println("开始+++++++++++++")
  //最佳实践:我们通常在伴生对象中实现 new 一个伴生类实例
  def apply(): ApplyTest = {
    println("this is the apply method in object")
    new ApplyTest()       //创建伴生类实例
  }
  println("结束+++++++++++++")
}

一般的,我们使用 ApplyTest() 则是伴生对象调用apply()方法,对于我们要去new一个伴生类实例,我们一般在对应的伴生对象内的apply方法内去new

(该代码感兴趣的小伙伴可以拿去测试,代码很简单!)

举例子:

    对于数组Array来说,有两种实现对象的方式

1 object ArrayTest extends App {
2    val a = Array(1,2,3,4)
3    val b = new Array[Int](4)
4 }

二者都属于定长数组;a的写法其实是b写法的语法糖 (更精简),我们可以对Array的apply源码进行查看:

1 /** Creates an array of `Int` objects */
2   // Subject to a compiler optimization in Cleanup, see above.
3   def apply(x: Int, xs: Int*): Array[Int] = {
4     val array = new Array[Int](xs.length + 1)
5     array(0) = x
6     var i = 1
7     for (x <- xs.iterator) { array(i) = x; i += 1 }
8     array
9   }

该apply方法是在其Array的伴生对象中实现(主要在伴生对象中实现了Array的基本操作),第四行的实现即是我们声明Array的b写法

 

转载于:https://www.cnblogs.com/zhixiangshu/p/10063579.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值