skip to Main Content

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


  1. 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.

    Login or Signup to reply.
  2. 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).

    Login or Signup to reply.
  3. 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 in onCreateView(). For all the places where you actually use it, you would use binding, 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.

    Login or Signup to reply.
  4. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search