Skip to content

Instantly share code, notes, and snippets.

@mileskrell
Created October 21, 2019 16:36
Show Gist options
  • Save mileskrell/1993347e720319d731aa7da157a10f07 to your computer and use it in GitHub Desktop.
Save mileskrell/1993347e720319d731aa7da157a10f07 to your computer and use it in GitHub Desktop.
A note on being careful with scope functions

This is something I encountered during development of my project Text Torch, and I thought it was interesting enough to write it down here.

The following code snippets are both executed within the context of a fragment. There is a big difference between the following two code snippets. In the first, "fragmentManager" is a property on the fragment containing the whole code snippet. But in the second, it's a property on the newly-created SortTypeDialogFragment, and it actually ends up returning null!

tl;dr: always keep your context in mind when using Kotlin's scope functions, especially when the context inside the scope function is for an object of the same class as the context outside the scope function.

// This did what I wanted
val sortTypeDialogFragment = SortTypeDialogFragment(socialRecordsViewModel.sortType.radioButtonId, socialRecordsViewModel.reversed)
    .apply { setTargetFragment(this@StatsFragment, SortTypeDialogFragment.REQUEST_CODE) }
fragmentManager?.let { fm ->
    sortTypeDialogFragment.show(fm, null)
}
// This did *not* do what I wanted!
SortTypeDialogFragment(socialRecordsViewModel.sortType.radioButtonId, socialRecordsViewModel.reversed)
    .apply {
        setTargetFragment(this@StatsFragment, SortTypeDialogFragment.REQUEST_CODE)
        fragmentManager?.let { fm ->
            show(fm, null)
        }
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment