I have a code which looks like this ```class TeaMa...
# announcements
a
I have a code which looks like this
Copy code
class TeaMaker {
    private lateinit var tea: Tea

    fun prepareTea() {
        tea = Tea()
    }

    fun addSugar() {
        tea.add(Sugar())
    }
}

class Restaurant {
    ...
    //In some method
    val teaMaker = TeaMaker()

    teaMaker.prepareTea()
    teaMaker.addSugar()
}
The problem is when i call addSugar I get the lateinit not initialized exception. I tried setting up debugger but found it is initialised. Am I missing something?
a
In the real program, is this:
Copy code
teaMaker.prepareTea()
teaMaker.addSugar()
really done sequentially, or are there multiple threads? If there are, it could explain why the problem goes away when you attach debugger
👍 1
d
What probably happened is this:
Tea()
returned
null
👍 1
When the compiler thought it never should
I've run into this issue before
The problem with it is that
lateinit
property is not fail-safe in this case and results in wrong error
👍 1
Try adding
!!
and see if error changes
b
both of these functions have a
void
/
unit
return type, so I highly doubt
!!
will change anything.
d
tea = Tea()!!
a
The problem was rather complex and related to lifecycle of activity in android. In the actual code I had view returned in prepareTea() method, the view wasn't not being fully inflated before accessing its property that's why it threw an exception.
What I did was make the property val instead of lateinit var to fix the error.