scala学习笔记4(apply方法)

class ApplyTest{
  def apply() = "This apply is in class"
  def test{
    println("test")
  }
}

//放在 object 对象中的方法都是静态方法
//由于 object 中的方法和属性都是静态的,所以就是单例的理想载体
//object 本身就是一个单例对象
object ApplyTest{
  var count = 0
  def apply() = new ApplyTest
  def static{
    println("I am a static method")
  }
  def incr = {
    count = count + 1
  }
}

object UseApply extends App{
  
  ApplyTest.static
 
  //当我们使用 "val a = ApplyTest()" 会导致 apply 方法的调用并返回该方法调用的值,也就是 ApplyTest 的实例化对象
  val a = ApplyTest()
  a.test
  
  // class 中也可以使用 apply 方法  
  val b = new ApplyTest
  println(b())
  
  for(i <- 1 to 10){
    ApplyTest.incr
  }
  println(ApplyTest.count)
}
</pre>运行结果:<img src="http://img.blog.csdn.net/20140902191033250?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvbHNzaGxzdw==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" /><pre>
原文地址:https://www.cnblogs.com/zhangyunlin/p/6168214.html