why do we make bindings `lateinit` ? we are gonna ...
# getting-started
g
why do we make bindings
lateinit
? we are gonna use that property as soon as our activity/fragment is created, so what's the goal/gain here by using
lateinit
?
j
What would you suggest as an alternative?
g
just making it null, and then assigning value to it onCreate/onCreateView?
j
Then you would have to deal with nullability every time you access it. You could technically assign null to it as well, so you would have less safety in this respect
g
what about creating two properties like
_binding
and
binding
? one immutable and one mutable. then we wouldn't have to deal with nullability
j
Could you please spell that out in actual code? I fail to see how that would be better than
lateinit
m
Yes you could do it like
_binding
but you need to know that we do that in purpose, so we can clear the binding and set it back to
null
in
onDestroy
to make it eligible for garbage collection, if you have this use case you can do it this way, otherwise
lateinit
is enough.
g
@Joffrey I am not saying it's better than
lateinit
. I just want to know what we gain by using
lateinit
.
Copy code
private var _binding: FragmentMyBinding? = null
    private val binding get() = _binding!!

    //or

    private lateinit var binding: FragmentMyBinding
if we don't gain anything by using
lateinit
, why people still use it instead of using the first approach? I still can make
_binding
null to clear the binding.
j
To answer what we gain by using lateinit, I need to know what you're comparing it to. The code you provided still allows code to set the
_binding
property to null later, so
binding
doesn't have a clear scope for its safe usage. The error thrown by
binding
would also be quite generic. If you want to fix these little details, you'll end up with even more code. But to be frank this pattern is exactly what the
lateinit
syntax is meant to express. So basically by using
lateinit
you have less code, you express the intent better, and it's slightly more constrained.
👍 1
🙌 1
h
I wish, there would be lateinit val
m
Lazy is lateinit val
g
So basically by using it you have less code, you express the intent better, and it's slightly more constrained
this is what I was inquiring about. Thanks @Joffrey!
👍 1
h
You can’t use lazy if you assign the value from another call/scope, like in createBindings
j
In activities, as I didn't need nullability, I was using
val
+ Lazy without issues