i just found out about lateinit, this is super coo...
# getting-started
l
i just found out about lateinit, this is super cool so that we don’t have to construct something using null 🥰
k
In practice, I've found very few cases where the use of
lateinit
was more readable than other ways.
l
data class require all properties to be initialized unless they’re lateinit’d
and it’s a million time better than initialize uninitializable properties to null
and if, somehow, you forget to initialize it you have a clear and concise message about how you forgot to init a lateinit instead of some ugly null exception
k
But
lateinit
is not allowed on primary constructor parameters. So you would have to have it in a property defined inside the class body instead, and then it wouldn't take part in the methods automatically created by the data class such as
equals
.
r
But
lateinit
is not allowed on primary constructor parameters
That would be rather pointless. How do you not initialize a passed in value?
j
What is your use case where you’d want to
lateinit
a property of a data class? As @Klitos Kyriacou alluded, it would defeat the purpose of using a data class anyway. I’m of the opinion
lateinit
should be avoided in most cases, as it is effectively breaking null safety and lead to runtime exceptions. There’s usually better (safer) ways to handle things. Only time I’d usually make an exception is for things like butterknife or mockito where we want to inject some value.