Skip to content

Instantly share code, notes, and snippets.

@fullkomnun
Last active December 3, 2017 07:32
Show Gist options
  • Save fullkomnun/01f4e17a437372b391fa6760bf9a9b96 to your computer and use it in GitHub Desktop.
Save fullkomnun/01f4e17a437372b391fa6760bf9a9b96 to your computer and use it in GitHub Desktop.
Get activity from context - iterative vs tail recursion
private fun Context?.findActivity_iter(): Activity? {
var context = this
while (context is ContextWrapper) {
if (context is Activity) {
return context
}
context = context.baseContext
}
return null
}
private tailrec fun Context?.findActivity_rec(): Activity? =
when (this) {
is Activity -> this
is ContextWrapper -> baseContext.findActivity_rec()
else -> null
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment