https://kotlinlang.org logo
#announcements
Title
# announcements
a

Ankur Gupta

08/07/2019, 4:31 AM
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

arekolek

08/07/2019, 6:00 AM
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

Dico

08/07/2019, 6:39 PM
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

Brandon Ward

08/16/2019, 2:43 PM
both of these functions have a
void
/
unit
return type, so I highly doubt
!!
will change anything.
d

Dico

08/16/2019, 5:39 PM
tea = Tea()!!
a

Ankur Gupta

08/18/2019, 7:44 AM
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.