https://kotlinlang.org logo
#codereview
Title
# codereview
e

Ellen Spertus

02/11/2020, 7:55 PM
Could someone look over this code?
Copy code
private fun getIntent(utterance: String): Intent =
  IntentRunner.processUtterance(utterance)?.let { intent ->
    intent.resolveActivityInfo(packageManager, intent.flags)?.let { activityInfo ->
      if (activityInfo.exported) intent else null
    }
  } ?: Intent(
    Intent.ACTION_VIEW,
    Uri.parse("${BASE_URL}${URLEncoder.encode(utterance, ENCODING)}")
  )
The idea is that I want the bottom
Intent
to be returned if either
processUtterance()
returns null,
resolveActivityInfo()
returns null, or
activityInfo.exported
is false. I welcome comments on correctness and style.
t

trevjones

02/11/2020, 8:00 PM
IMO: this looks like abuse of the nullability chaining that kotlin provides. It's a cool trick but is usually harder to read, and change than just capturing a few val's and doing a few if/else blocks.
e

Ellen Spertus

02/11/2020, 8:05 PM
Thanks, @trevjones! It will be interesting to see what others say. I do want to write code that is simultaneously maintainable and idiomatic and appreciate the guidance I get here.
👍 1
t

trevjones

02/11/2020, 8:11 PM
would be less nasty if the nested let wasn't there.
Copy code
IntentRunner.processUtterance(utterance)?.takeIf { it.resolvesToExportedActivity() }
  ?: Intent(ACTION_VIEW, Uri.parse("${BASE_URL}${URLEncoder.encode(utterance, ENCODING)}"))

fun Intent.resolvesToExportedActivity() =
  resolveActivityInfo(packageManager, flags)?.exported == true
1
3 Views