5 quarters Have a treat! Have a treat! Have a trea...
# getting-started
y
5 quarters Have a treat! Have a treat! Have a treat! Have a treat! No treats! What I don't understand is that according to the repeat logic, the tricOrTreat function is called 4 times with the parameter 'fasle', so shouldn't it output '5 quarters' 4 times? Why are there 4 times of 'Have a treat!'? If (extraTreat!=null) doesn't this branch enter?🤔
🧵 1
🧵 1
y
Note that the
treatFunction
is actually
treat
, because that's the value that
trickOrTreat
returns in that case. It also calls
extraTreat
in place, but it doesn't return it or anything, so it's only called once
y
Aren't println (extraTreat (5)) and println ("Have a treat!") both outputs?
Even stranger, if we swap the
treatFunctional()
inside the repeat function with the
tricFunctional()
outside the function, it would look like this:
Copy code
fun main() {
    val treatFunction = trickOrTreat(false) { "$it quarters" }
    val trickFunction = trickOrTreat(true, null)
     repeat(4) {
        trickFunction()
    }
    treatFunction()
}
The result obtained is:
Copy code
5 quarters
No treats!
No treats!
No treats!
No treats!
Have a treat!
Why did "5 quarters" become the first output text content after executing TrickFunctional() 4 times first?
r
It's a confusing example but I'm pretty sure that's the point. Just remember that
trickOrTreat
is a function that takes a function and returns a function. Once you understand the difference between these three functions, everything else should make sense
y
This should clear things up a bit:
Copy code
val trick = {
    println("trick")
}

val treat: () -> Unit = {
    println("treat")
}


fun trickOrTreat(isTrick: Boolean, extraTreat: ((Int) -> String)?): () -> Unit {
    if (isTrick) {
        return trick
    } else {
        if (extraTreat != null) {
            println(extraTreat(5))
        }
        return treat
    }
}

fun main() {
    val treatFunction = trickOrTreat(false) { "hello from extra treat! $it" }
    val trickFunction = trickOrTreat(true, null)
    println("--Begin using returned functions--")
    treatFunction()
    trickFunction()
}
This prints:
hello from extra treat! 5
--Begin using returned functions--
treat
trick
y
I have reviewed the official tutorial on functions and variables again. I think I may have misunderstood before. If we consider TrickFunction as a variable that stores the execution result of the function TrickOrTreat(), then this result makes sense.