'Why is get () used in this viewBinding example?
I want to know why "private val binding get() = _binding!!" was used here?
private var _binding: ResultProfileBinding? = null
private val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
_binding = ResultProfileBinding.inflate(inflater, container, false)
val view = binding.root
return view
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
Solution 1:[1]
I am assuming that you got that code from this page in the documentation.
Their objective is to give you a way to access the _binding value without needing to deal with the fact that _binding can be null. In the portion of their example that you did not include, they have a comment on binding that points out that it can only be used between onCreateView() and onDestroyView(). If you are in a part of your code where you can guarantee that your code will execute between those two callbacks, you can reference binding, which will return the value of _binding coerced into a not-null type (ResultProfileBinding instead of ResultProfileBinding?).
However, if you get it wrong, and you try referencing binding before onCreateView() or after onDestroyView(), you will crash with a NullPointerException.
Personally, I would avoid this approach.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | CommonsWare |
