Yhcs Ami
01/10/2025, 3:57 AMYoussef Shoaib [MOD]
01/10/2025, 4:41 AMtreatFunction
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 onceYhcs Ami
01/10/2025, 7:53 AMYhcs Ami
01/10/2025, 8:00 AMtreatFunctional()
inside the repeat function with the tricFunctional()
outside the function, it would look like this:
fun main() {
val treatFunction = trickOrTreat(false) { "$it quarters" }
val trickFunction = trickOrTreat(true, null)
repeat(4) {
trickFunction()
}
treatFunction()
}
Yhcs Ami
01/10/2025, 8:00 AM5 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?Robert Williams
01/10/2025, 10:52 AMtrickOrTreat
is a function that takes a function and returns a function. Once you understand the difference between these three functions, everything else should make senseYoussef Shoaib [MOD]
01/10/2025, 9:37 PMval 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
Yhcs Ami
01/11/2025, 7:02 AM