【Scala】看代码,初步了解Apply方法

class ApplyTest(val name:String) {
  /**
   * apply源码
   * def apply(x: Int, xs: Int*): Array[Int] = {
   *    val array = new Array[Int](xs.length + 1)
   *    array(0) = x
   *    var i = 1
   *    for (x <- xs.iterator) { array(i) = x; i += 1 }
   *    array
   * }
   */
}

/**
 * apply方法是scala中特殊的方法,某种程度上可以理解为是class的一种构造方法,通过apply创建对象实例
 * apply方法必须定义在类的伴生对象中
 * 在创建对象实例时,如果不加new,就回去伴生对象中寻找有没有apply方法,有就调用,没有就报错
 */
 
//伴生对象
object ApplyTest {
  def apply(name:String): ApplyTest = new ApplyTest(name)
}

object Use {
  def main(args: Array[String]): Unit = {
    //通过new创建
    val qiuBojun = new ApplyTest("QiuBojun")
    //通过调用apply方法创建
    val leiJun = ApplyTest("LeiJun")
  }
}
原文地址:https://www.cnblogs.com/zzzsw0412/p/12772404.html