Search code examples
kotlinexecution

Order of execution - Kotlin


I have tried to debug the next program to understand the execution order, however I'm still confused about the execution order

fun foo(): String{
    println("Calculating foo...")
    return "foo"
}

fun main(args: Array<String>) {
    println("First ${foo()}, Second ${foo()}!")
}
// Result:
//
// Calculating foo...
// Calculating foo...
// First foo, Second foo!

// I though the execution would show something like this:
//
// First Calculating foo...foo,
// Second Calculating foo...foo!

Isn't main the initial function to be executed? If it is, then println would be the 1st sentence, as such (for me) the execution would start from left to right (am I correct?), so... if it is the first word to be displayed would be First ,then it would be called the foo() function and this would return "foo", that would be extrapolated to string again => ${} ... am I right ? If not, what I'm misunderstanding ?

Thanks for any clarification.


Solution

  • You can think about it like this

    1. Execute main() function.
    2. Evaluate argument to println() function.
      • "First ${foo()}, Second ${foo()}!" is using string interpolation, so we need to first interpolate the string.
    3. Interpolate first ${foo()}, by calling foo()
    4. First foo() prints "Calculating foo..."
    5. Interpolate second ${foo()}, by calling foo()
    6. First foo() prints "Calculating foo..."
      • Now we have the interpolated string First foo, Second foo!
    7. Execute println("First foo, Second foo!")