Skip to content Skip to sidebar Skip to footer

What Is The Difference Between Binding And _binding?

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: ResultPr

Solution 1:

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.

Post a Comment for "What Is The Difference Between Binding And _binding?"