Search code examples
androidandroid-viewbinding

Purpose of with & without underscore variable view binding


code example

What is the purpose of defining 2 variable in this tutorial? Why don't we use 1 variable instead and accessing view with it?

https://developer.android.com/topic/libraries/view-binding#usage


Solution

  • The getter on the second variable (binding) uses the !! operator to assert that the variable is non-null when accessed.

    Essentially the backing field (_binding) is nullable in order to represent the state before onCreateView and after onDestroyView whereas the getter provides an easy way to access the field without scattering null checks or assertions elsewhere in your code.