I was declared a binding object in a fragment as lateinit var binding: EditInsuranceDialogBinding
but a colleague said "This is a bad practice and Binding object should be Optional . "
So in the declaration will be instead like this: var binding: EditInsuranceDialogBinding? = null
, initialised in the onCreateContentView
and make it null
in the onDestroyView
I want to know what is the best to choose the type of Binding (optional or not)? and does lateinit cost a lot in the compiler and memory ? When we should NOT choose lateinit and when we should use it?
It is possible that your colleague really meant that the binding object should be wrapped in
Optional
.lateinit var
is not evil. However, it is not ideal for all circumstances.In this case, a binding object has a specific lifecycle, and we need to stop using it after
onDestroyView()
. If you declare the property as:...then you have no way of setting it to something after
onDestroyView()
that says "we do not have a valid binding". It is easy to wind up having code in a fragment that runs afteronDestroyView()
, and that code needs to know that it is not safe to use the binding. There is no way to create anEditInsuranceDialogBinding
instance that represents the "not safe to use the binding" state.The alternative that you chose is reasonable:
...where you set
binding
tonull
inonDestroyView()
.You could also go with:
...where you set
binding
back toOptional.empty()
inonDestroyView()
. There are also custom binding delegates, such as this one, that you could use.No.
I try to only use
lateinit
when I am very certain that I will initialize it before use.