scala apply方法和update方法

Posted on 2022-06-26 17:23  foghorn  阅读(26)  评论(0编辑  收藏  举报

示例代码1

class TestApplyClass {
  def apply(param: String): String = {
    println("apply method called, parameter is: " + param)
    
    return "Hello World!"
  }
}


val myObject = new TestApplyClass()
println(myObject("param1"))

输出为:
apply method called, parameter is: param1
Hello World!

示例代码2

object TestApplySingleObject {
  def apply(param1: String, param2: String): String = {
    println("apply method called")
    
    return param1 + " and " + param2
  }
}

// 单例对象不需要 new
val group = TestApplySingleObject("zhangfei", "liubei")
println(group)

输出:
apply method called
zhangfei and liubei

可以看出,在执行TestApplySingleObject("zhangfei", "liubei")时调用了apply方法,并且把"zhangfei and liubei"作为返回值,赋值给group变量。


输出:
apply method in object is called
Greeting menthod in class is called.
apply method in class is called!

Copyright © 2024 foghorn
Powered by .NET 9.0 on Kubernetes