Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use function types and lambda expressions in Kotlin: Android Basics with Compose #160

Open
1-liz opened this issue Nov 11, 2024 · 0 comments

Comments

@1-liz
Copy link

1-liz commented Nov 11, 2024

URL of codelab
https://developer.android.com/codelabs/basic-android-kotlin-compose-function-types-and-lambda?continue=https%3A%2F%2Fdeveloper.android.com%2Fcourses%2Fpathways%2Fandroid-basics-compose-unit-2-pathway-1%23codelab-https%3A%2F%2Fdeveloper.android.com%2Fcodelabs%2Fbasic-android-kotlin-compose-function-types-and-lambda#5

In which task and step of the codelab can this issue be found?
Step 4: use functions as a data type

Describe the problem
One thing that is not clear in the training is why "5 quarters" is always printed even when I comment out the call to the treatFunction() and re-run the code.

If I never make the call to the treatFunction, how does the code get to the else component and execute the println?

Steps to reproduce?
here is my code: see how treatFunction() line is commented out with // Also, I don't see "Have a treat" printed, so I know that is working. But "5 quarters" still prints on the first line. Why?

fun main() {
val treatFunction = trickOrTreat(false) {"$it quarters"}
val trickFunction = trickOrTreat(true, null)
trickFunction()
//treatFunction()
}

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

val trick = {
println("No treats!")
}
val treat = {
println("Have a treat!")
}

Versions
I'm using Kotlin playground to test the code as instructed.

Additional information
screenshot included:

Kotlin question2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant