Search code examples
androidkotlininheritanceinterfacereusability

How can I reuse private functions in kotlin classes?


I have these two classes that contain the same function.

class UpInfoDayFragment : UpDayFragment<FragmentNavSituationDayBinding>() {
    ...
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        setupViews()
        setupWhenItemDeletedFunctionality()
    }

    private fun setupWhenItemDeletedFunctionality() {
        viewModel.itemDeleted.observe(viewLifecycleOwner) { dayDeleted ->
            if (dayDeleted) {
                navigateToPreviousFragment()
                showMessage(binding.root, R.string.day_deleted)
            }
        }
    }
}
class UpInfoTopicFragment : UpTopicFragment<FragmentNavIdeasTopicBinding>() {
    ...
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        setupViews()
        setupWhenItemDeletedFunctionality()
    }

    private fun setupWhenItemDeletedFunctionality() {
        viewModel.itemDeleted.observe(viewLifecycleOwner) { topicDeleted ->
            if (topicDeleted){
                navigateToPreviousFragment()
                showMessage(binding.root, R.string.notebook_deleted)
            }
        }
    }
}

I cannot reuse this function using inheritance because these classes already have superclasses. I cannot use interfaces because these functions would need to be public. How could I reuse this code?


Solution

  • To reuse this private function between these classes, derived from the same parent, while keeping it private, you may do the following trick:

    1. Create a new interface, and define public extension function for parent class inside this interface:
    interface UpInfoDayFragmentExtended {
        fun <T> UpInfoDayFragment<T>.setupWhenItemDeletedFunctionality() {
            //...
        }
    }
    
    1. Make UpInfoDayFragment & UpInfoTopicFragment implement this interface.

    Voila! Now setupWhenItemDeletedFunctionality() function is accessible from inside these classes (and actually any other, which will implement this interface), but is hidden for others, like a private method!