示例代码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!