1. 程式人生 > >伴生類和伴生物件(apply方法的實踐)

伴生類和伴生物件(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寫法