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.
4
Answers
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. Withoutget()
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.
In this case, you don’t. It’s very messy in my opinion.
Simply use:
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
).If you use it like this, you have a very explicit way of setting
binding
– you have to do it using_binding
(which would probably just happen once inonCreateView()
. For all the places where you actually use it, you would usebinding
, which both checks if_banding
has actually been set, and cannot accidentally be changed as it is immutable, thereby saving you from potential bugs.That being said – I would probably go with a
lateinit var
as well, and lose all the null checking, but that is a matter of personal taste I think.using get() after the variable name makes it assign to the value when we each time trying to access this variable
as mentioned above without get() the variable will be assigned immediately when this class instantiated