What is the difference between binding and _binding?

Viewed 540

I am trying to understand the implementation of view binding in a fragment and I found that it is different from an activity.

In an activity:

private lateinit var binding: ResultProfileBinding

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    binding = ResultProfileBinding.inflate(layoutInflater)
    val view = binding.root
    setContentView(view)
}

In a fragment:

private var _binding: ResultProfileBinding? = null
private val binding get() = _binding!!

override fun onCreateView(
    inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    _binding = ResultProfileBinding.inflate(inflater, container, false)
    val view = binding.root
    return view
}

override fun onDestroyView() {
    super.onDestroyView()
    _binding = null
}

Now my question is, why do we have binding and _binding in the fragment? What is this line is doing and what is it's purpose?

private val binding get() = _binding!!
1 Answers

In the second example, the _binding property is nullable so as to allow a state before it has been 'initialised'. Then the binding property has a getter to provide convenient access, given that the backing field (_binding) has been initialised.

The specific line you're referring to means that when you try to access binding, it will return _binding. However the null assertion operator (the !!) adds the extra assertion that _binding isn't null.

Really all that you've done is created an analogue of the lateinit property, and actually if you look at the decompiled bytecode of a lateinit declaration, they amount to the same.

However, as @Tenfour04 pointed out, the subtle difference here is that the second approach allows you to set the backing field back to null, whereas you can't do this with a lateinit property. When you use a binding in a fragment, it's recommended to null out the binding in onDestroyView in order to avoid memory leaks, so this is why they've gone with this approach in a fragment.

Related