Search code examples
androidkotlinkotlin-null-safety

Kotlin safe call (?.) implementation


I could solve it with cumbersome methods so would really appreciate if you don't post a workaround but rather documented solution.

I'm trying to add following code snippet into onCreateView() of a Fragment but "thanks" to safe call (or my code design) things got complicated. AfterTabLayoutMediator(activity part Kotlin shows warning to add safe call (?.) after activity (equivalent to getActivity in Java) which could be null.

Original code snippet before trying any solution

TabLayoutMediator(activity.findViewById(R.id.tabs), view.findViewById(R.id.view_pager),
                TabLayoutMediator.OnConfigureTabCallback { tab, position ->
                    // Styling each tab here
                    tab.text = mValueHeadlineCategoryList[position]
                }).attach()

1) Trying to solve by adding safe call (failed)

Adding safe call now goes against TabLayoutMediator input parameter and I get type mismatch Required:TabLayout Found:TabLayout? warning on TabLayoutMediator.

TabLayoutMediator(activity?.findViewById(R.id.tabs), view.findViewById(R.id.view_pager),
            TabLayoutMediator.OnConfigureTabCallback { tab, position ->
                tab.text = mValueHeadlineCategoryList[position]
            }).attach()

2) Trying to solve by null check before safe call (failed)

Adding null check, but now Kotlin gives warning on TabLayoutMediator(activity part that reads Smart cast to 'FragmentActivity' is impossible, because 'activity' is a property that has open or custom gette

if (activity != null) {
            TabLayoutMediator(activity.findViewById(R.id.tabs), view.findViewById(R.id.view_pager),
                TabLayoutMediator.OnConfigureTabCallback { tab, position ->
                    tab.text = mValueHeadlineCategoryList[position]
                }).attach()
        }

Solution

  • simple fix : you can do this

       activity?.let { instance ->
                TabLayoutMediator(instance.findViewById(R.id.tabs), view.findViewById(R.id.view_pager),
                    TabLayoutMediator.OnConfigureTabCallback { tab, position ->
                        tab.text = mValueHeadlineCategoryList[position]
                    }).attach()
    }