In Kotlin, the function declaration syntax allows you to write equals sign before the curly braces.
Consider these two examples:
- Without
=sign:
fun foo1() {
println("baz1")
}
The code inside the body gets executed by just calling foo1().
- With
=sign:
fun foo2() = {
println("baz2")
}
Here, when foo2() is called, nothing happens, but to get the body executed one can write foo2()().
What is the difference in these two declarations and why do they behave differently?
You can run the code using the following program:
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.