在Kotlin中,函数声明语法允许在花括号前写等号.
考虑这两个例子:
- 没有
=
号标志:
fun foo1() {
println("baz1")
}
体内的代码只需调用foo1()
即可执行.
- With
=
sign:
fun foo2() = {
println("baz2")
}
Here, when foo2()
is called, nothing happens, but to get the body executed one can write foo2()()
.
这两个声明和why do they behave differently?有什么区别
可以使用以下程序运行代码:
fun main() {
foo1()
foo2()
}
/*
This code example produces the following results:
baz1
*/
This question, though having not much meaning, is [intentionally asked and answered by the author][1], because a few questions have already been posted where people got problems because of incorrect function definitions.