scala_apply

    如果你不看spark源码的话,有前面scala的知识就够了,但是,如果你要玩spark的话,你不看源码是不行的。

package cn.chinahadoop.scala
class Basic4 {
}
class ApplyTest {
  def test {
    println("test")
  }
}
object ApplyTest {
  def static {
    println("i'am a static method ")
  }
}
object Basic4 extends App {
  //  new ApplyTest().test;
  ApplyTest.static;
}


结果:

i'am a static method

注意ApplyTest是用object修饰的,而不是class,且static在scala中不是一个关键字!

package cn.chinahadoop.scala
class Basic4 {
}
class ApplyTest {
  def test {
    println("test")
  }
}
object ApplyTest {
  def apply()=new ApplyTest
  
  def static {
    println("i'am a static method ")
  }
}
object Basic4 extends App {
  //  new ApplyTest().test;
 // ApplyTest.static;
  val a=ApplyTest()//a 其实已经是applytest的实例了
  //因为applytest已经调用了apply()方法
  //类名加上一个括号已经调用了object的apply方法
  //测试一下
  a.test
}

结果为:

test

那么class有没有apply方法呢?

类名加括号是调用object方法,而你的对象加上括号就调用的apply方法。如t()调用的是class中的apply()方法。

package cn.chinahadoop.scala
class Basic4 {
}
class ApplyTest {
  def apply() = "APPLY"
  def test {
    println("test")
  }
}
object ApplyTest {
  def apply() = new ApplyTest
  def static {
    println("i'am a static method ")
  }
}
object Basic4 extends App {
  //  new ApplyTest().test;
  // ApplyTest.static;
  //  val a=ApplyTest()//a 其实已经是applytest的实例了
  //因为applytest已经调用了apply()方法
  //类名加上一个括号已经调用了object的apply方法
  //测试一下
  // a.test
  var t = new ApplyTest();
  println(t())
  println("直接打印t" + t)
}

结果为:

APPLY
直接打印tcn.chinahadoop.scala.ApplyTest@40773f4b

直接打印t是打印了一个前面是路径后面是一个hashcode。


模拟单例

package cn.chinahadoop.scala
class Basic4 {
}
class ApplyTest {
  def apply() = "APPLY"
  def test {
    println("test")
  }
}
object ApplyTest {
  var count = 0;
  def apply() = new ApplyTest
  def static {
    println("i'am a static method ")
  }
  def incr = {
    count = count + 1
  }
}
object Basic4 extends App {
  //  new ApplyTest().test;
  // ApplyTest.static;
  //  val a=ApplyTest()//a 其实已经是applytest的实例了
  //因为applytest已经调用了apply()方法
  //类名加上一个括号已经调用了object的apply方法
  //测试一下
  // a.test
  //  var t = new ApplyTest();
  //
  //  println(t())
  //  println("直接打印t" + t)
  for (i <- 1 to 10) {
    ApplyTest.incr
  }
  println(ApplyTest.count)
}

结果为:

10


总结:

object可以用来模拟static,也可以用来模拟单例,其实际就是一个单例。object不产生实例,他只代表他自己。


本文出自 “陈生龙” 博客,谢绝转载!

你可能感兴趣的:(scala,apply)