Labels

To better understand this, let's include a label where the execution starts, and also on each of the places were the execution can be resumed:

suspend fun getUserSummary(id: Int): UserSummary {
// label 0 -> first execution
logger.log("fetching summary of $id")
val profile = fetchProfile(id)

// label 1 -> resuming
val age = calculateAge(profile.dateOfBirth)
val terms = validateTerms(profile.country, age)

// label 2 -> resuming
return UserSummary(profile, age, terms)
}

Now, let's pretend that we can somehow receive the label that indicates which part of the code to execute. Then, we could write a when statement to separate the code to be executed:

when(label) {
0 -> { // Label 0 -> first execution
logger.log("fetching summary of $id")
fetchProfile(id)
return
}
1 -> { // label 1 -> resuming
calculateAge(profile.dateOfBirth)
validateTerms(profile.country, age)
return
}
2 -> // label 2 -> resuming and terminating
UserSummary(profile, age, terms)
}
Notice that this snippet and many more in this chapter are a simplified representation of the generated bytecode, and some of them are pseudo Kotlin. I don't intend to transform the bytecode generated by the compiler into valid Kotlin, but rather to give you a fairly accurate idea of how it works.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.21.104.183