I was following the google codelab. There I came across the following code:
class Calculator: Fragment() {
private var _binding: FragmentCalculatorBinding? = null
private val binding get() = _binding!!
}
What is the need for the get()
?
We can do this in the following way:
class Calculator: Fragment() {
private var _binding: FragmentCalculatorBinding? = null
private val binding = _binding!!
}
The explaination given there was:
Here, get()
means this property is "get-only". That means you can get the value, but once assigned (as it is here), you can't assign it to something else.
but I don't understand it. Please help me with this.
CodePudding user response:
The whole point in having a second property here is to allow the first property to be set back to null. (The second property is for convenience and should only be used when the fragment is known to be attached to an Activity.) Using a getter means it does the evaluation _binding!!
each time it is accessed. Without get()
it evaluates it once when the class is instantiated and assigns the result to a backing field. Since _binding
is null at class instantiation time, this would be guaranteed to fail. And even if it didn’t fail, it would have an outdated reference if the fragment got detached and reattached.
Your description of what “get only” means is inverted. Either the code lab got their explanation backwards or you paraphrased it backwards.
CodePudding user response:
In this case, you don't. It's very messy in my opinion.
Simply use:
private lateinit var binding: FragmentCalculatorBinding
It's does the same thing as your existing code - throws exception if you use the variable before instantiate it.
Keep in mind that you must instantiate it before using it (the whole point of lateinit var
).