I have a val, except I don't know what it will be ...
# announcements
t
I have a val, except I don't know what it will be until way later (like after some network stuff). but once it's set it should be immutable. Is there a pattern for this type of thing? More of a FP question than kotlin I know.
s
A
private lateinit var
and (public)
val
accessor could do it.
t
Sorta, It's all in the same class though. I guess I could break it out.
s
If it's all in the same class, I don't personally see an issue with keeping it as
lateinit var
. It's not ideal, but so long as it isn't accessible outside the scope of the class, it shouldn't be a problem. Maybe add a comment saying it shouldn't be re-initialized.
t
yeah. it's just one of those things that if it changes, stuff blows up. So I wanted the compiler to catch it. I'll try hiding it a bit.
n
Personally I would say that it's more ideal to have two separate classes
at the end of the day, lateinit is just a slightly better version of two-phase initialization
you create the object but it's not the "real" object yet
it's waiting for some moment M when it can become the real object
Instead of having one class C which is in a borked state prior to M and only becomes "real" after M, you have two classes. C1 is the class you construct immediately. It does not have this member at all. C2 is the class you construct after M occurs. C2 is constructed from a C1 and whatever information you get at M.
j
depending on details, the
lazy
delegate could work?