Scala的Apply方法

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总结:

  1. val testA = ApplyTest() ---->类名() 调用的是伴生对象Object的apply()方法
  2. val testB = new ApplyTest;println(testB()) ----对象() 调用的是伴生类的Class的apply()方法(几乎没用)
    参考:SparkEnv.scala中的UnifiedMemoryManager
val memoryManager: MemoryManager =
      if (useLegacyMemoryManager) {
        new StaticMemoryManager(conf, numUsableCores)
      } else {
        UnifiedMemoryManager(conf, numUsableCores)
      }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值