What does `tailrec` do here? ```tailrec fun Conte...
# getting-started
t
What does
tailrec
do here?
Copy code
tailrec fun Context.activity(): Activity? = when {
  this is Activity -> this
  else -> (this as? ContextWrapper)?.baseContext?.activity()
}
l
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
imo this represents the intention better:
Copy code
fun Context.activity(): Activity? =
    generateSequence(this) { (it as? ContextWrapper)?.baseContext }
        .filterIsInstance<Activity>()
        .firstOrNull()
a
the
generateSequence
version is dramatically less efficient than the
tailrec
version