当我在下面运行代码时,未调用应用方法:
object Tester2 {
def apply(){
println("apply")
}
def main(args: Array[String]) {
Tester2
}
}
但是,如果我Tester2()在 main 方法中使用而不是Testerapply 方法,则会被调用
为什么需要 () 才能调用 apply 方法?
当我在下面运行代码时,未调用应用方法:
object Tester2 {
def apply(){
println("apply")
}
def main(args: Array[String]) {
Tester2
}
}
但是,如果我Tester2()在 main 方法中使用而不是Testerapply 方法,则会被调用
为什么需要 () 才能调用 apply 方法?
Tester2是一个对象名,一个值。表达式可能只包含单个值。您可以替换Tester2为2或"str"。
Tester2是一个结果类型为 的表达式Tester2.type。就像2是一个结果类型的表达式Int。
要调用apply方法,您应该像这样添加括号:
Tester2()
apply您可以不带括号显式调用方法:
Tester2.apply
当您调用 时Tester2,您将获得一个 Tester2 对象。当您调用 时Tester2(),您正在调用 Tester2 对象的 apply 方法。当使用语法糖 as 时,Scala 需要 '()' 来消除创建新对象或调用 apply() 之间的歧义Tester2()。