Angular Mac
Angular Mac

Reputation: 21

Android Dev in Kotlin, confused by tutorial

Im struggling with one of the android basics in kotlin code labs. Im a beginner who took up programming in lockdown for fun.

This is the tutorial in question

At the begining of the tutorial it says to get a nullable reference to binding named_binding, then use

private val binding get() = _binding!!

to get a version of it we can refer to without using the ? null safety thing. All good so far.

However in step four it shows the following code:

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

Why do we refer to _binding to inflate the view then binding in the next line when assigning the view?

Upvotes: 2

Views: 321

Answers (2)

tktschool
tktschool

Reputation: 116

This is best practice to protect someone modify _binding like _binding = null and you got error when access to _binding,

You should use binding.root instead _binding.root

Upvotes: 0

dominicoder
dominicoder

Reputation: 10175

Why do we refer to _binding to inflate the view then binding in the next line when assigning the view?

Two concepts to understand here.

  1. _binding is considered a backing property - that is, the actual variable reference that holds a value. In this case, the variable is a nullable type.
  2. binding is a standard property - that is, a thing that provides access to an underlying backing field. In this case, it's using _binding as a backing property as a minor convenience to expose _binding as a non-null.

So - since binding just exposes _binding as a non-null value, _binding must be set first. So that's why it's assigned the value of the inflate call. Also note that _binding is a var which means it can be re-assigned while binding is a val which means it can't. So trying to use binding when inflating the view would not compile.

Finally, why they use binding to get the view is unclear. Probably just for the sake of the convenience / consistency of using binding as the single property to reference the class binding. Using _binding?.root would work fine too.

Upvotes: 4

Related Questions