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?
but a colleague said "This is a bad practice and Binding object should be Optional . "
It is possible that your colleague really meant that the binding object should be wrapped in Optional
.
I want to know what is the best to choose the type of Binding (optional or not)?
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:
private lateinit var binding: EditInsuranceDialogBinding
...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 after onDestroyView()
, and that code needs to know that it is not safe to use the binding. There is no way to create an EditInsuranceDialogBinding
instance that represents the "not safe to use the binding" state.
The alternative that you chose is reasonable:
private var binding: EditInsuranceDialogBinding? = null
...where you set binding
to null
in onDestroyView()
.
You could also go with:
private var binding: Optional<EditInsuranceDialogBinding> = Optional.empty()
...where you set binding
back to Optional.empty()
in onDestroyView()
. There are also custom binding delegates, such as this one, that you could use.
and does lateinit cost a lot in the compiler and memory ?
No.
When we should NOT choose lateinit and when we should use it?
I try to only use lateinit
when I am very certain that I will initialize it before use.