伴生類和伴生對象(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寫法

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM