How to check if a lateinit variable is initialized in Kotlin?
Hello colleagues! I've been writing in Kotlin relatively recently and encountered a situation. I have a class where I use `lateinit var` for a property. It works, but I want to safely check if this property has already been initialized before accessing it. If I try to access an uninitialized `lateinit` variable, I get `UninitializedPropertyAccessException`, which breaks the program.
Here's an example of my code:
```kotlin
class MyApp {
lateinit var user: User
fun setup() {
// Here user may or may not be initialized
if (someCondition) {
user = User("Alice")
}
}
fun printUser() {
// I want to check if user is initialized to avoid the error
```
No answers yet.
Log in to leave an answer