Property Initialization in Kotlin: `by lazy` vs `lateinit` — when to use what?
Hi everyone! I'm switching from Java to Kotlin and I'm struggling to understand the difference between `by lazy` and `lateinit` for lazy property initialization. They both seem to solve the same problem — not initializing a property immediately when an object is created, but doing it later when it's actually needed.
But I keep getting confused about which option to choose. For example, I'm writing a simple Android ViewModel. I need to get a reference to a repository that is initialized via DI (Dagger/Hilt), but I don't want to make it nullable:
```kotlin
// Option with lateinit
class MyViewModel : ViewModel() {
lateinit var repository: MyRepository
fun loadData() {
// Here I'm sure repository is already initialized
repository.fetchData()
}
}
```
```kotlin
// Option with lazy
class MyViewModel : ViewModel() {
val repository: MyRepository by lazy {
MyRepository() // Or some factory
}
}
```
In the first case, I need to call `repository = ...` somewhere before