Initializing Properties in Kotlin: by lazy or lateinit — Which to Choose?
Hello everyone! I just started learning Kotlin and ran into a problem. I'm writing a small application, and I need to initialize some class properties, but their values become known only later — for example, after loading data or in `onCreate` for Android.
I know two approaches: `lateinit` and `by lazy`. But I can't figure out when to use which. Here's an example of my code:
```kotlin
class MyActivity : AppCompatActivity() {
private lateinit var userName: String
private val userAge: Int by lazy {
fetchUserAge() // this method may be called later
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
userName = "John" // lateinit initialization
}
private fun fetchUserAge(): Int {
return 25
}
}
```
The problem is that if I use `lateinit` for `userName`, the IDE complains if I try to make it `val`. And `by lazy` only works with `val`. Also, I heard that `latei
No answers yet.
Log in to leave an answer