伴生类和伴生对象(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写法

猜你喜欢

转载自www.cnblogs.com/zhixiangshu/p/10063579.html