object ApplyDemo {
def main(args: Array[String]): Unit = {
/**
* 会走到object的apply方法里面去
*/
val testA = ApplyTest()
testA.test()
println(testA)
println("---------------------------------")
/**
* 会走到类中的apply方法
*/
val testB = new ApplyTest
println(testB())
}
}
class ApplyTest {
/**
* 几乎不用
*/
def apply() = {
"====class ApplyTest invoked===="
}
def test() = {
println("===========> ApplyTest class test")
}
}
object ApplyTest {
println("enter ApplyTest object....")
var index = 0
def apply() = {
println("============object ApplyTest apply invoked==========")
new ApplyTest()
}
def incr() = {
index += 1
}
println("leave ApplyTest object...")
}
Object 和 Class 的名称相同,称Class定义叫做Object定义的伴生类,称Object定义叫做Class定义的伴生对象
关于apply总结:
- val testA = ApplyTest() ---->类名() 调用的是伴生对象Object的apply()方法
- val testB = new ApplyTest;println(testB()) ----对象() 调用的是伴生类的Class的apply()方法(几乎没用)
参考:SparkEnv.scala中的UnifiedMemoryManager
val memoryManager: MemoryManager =
if (useLegacyMemoryManager) {
new StaticMemoryManager(conf, numUsableCores)
} else {
UnifiedMemoryManager(conf, numUsableCores)
}