https://kotlinlang.org logo
#getting-started
Title
# getting-started
t

therealbluepandabear

03/19/2022, 3:24 AM
What does
tailrec
do here?
Copy code
tailrec fun Context.activity(): Activity? = when {
  this is Activity -> this
  else -> (this as? ContextWrapper)?.baseContext?.activity()
}
l

Luke

03/19/2022, 4:48 AM
It tells the compiler to generate bytecode that uses a loop instead of recursion. See the doc for more information: https://kotlinlang.org/docs/functions.html#tail-recursive-functions
1
e

ephemient

03/19/2022, 5:08 AM
imo this represents the intention better:
Copy code
fun Context.activity(): Activity? =
    generateSequence(this) { (it as? ContextWrapper)?.baseContext }
        .filterIsInstance<Activity>()
        .firstOrNull()
a

Adam Powell

03/19/2022, 3:05 PM
the
generateSequence
version is dramatically less efficient than the
tailrec
version
3 Views