Search code examples
androidkotlinnullnullpointerexceptionkotlin-lateinit

Kotlin null pointer when checking for null state


I have a codeblock with a simple null check that causes an exception

kotlin.UninitializedPropertyAccessException: lateinit property currentJob has not been initialized at com.plcoding.posterpalfeature.ui.MainViewModel.getCurrentJob(MainViewModel.kt:40) at com.plcoding.posterpalfeature.ui.MainViewModel.getJobsListFromApi(MainViewModel.kt:284)

I've tried this -->

 with(currentJob){
            if (this == null) {
                currentJob = jobsDataList.get(0) //maybe replace with accepted jobs depending on how details is implemented
            }
            else {
                //update the current job using job id to get fresh object
                currentJob = jobsDataList.filter {
                    it.job.job_id == currentJob.job.job_id
                }.get(0)
            }//should only ever be single object
        }

this

if (currentJob == null) {
                currentJob = jobsDataList.get(0) //maybe replace with accepted jobs depending on how details is implemented
            }
            else {
                //update the current job using job id to get fresh object
                currentJob = jobsDataList.filter {
                    it.job.job_id == currentJob.job.job_id
                }.get(0)
            }

and a when statement and they all throw the same exception

here is my variable

lateinit var currentJob: JobPW

Any ideas? This is really weird. I'm thinking of raising a bug report but I'm not sure where to do it.


Solution

  • You need set value for lateinit var variable before use it.

    To check variable is inited or not, you can check it with:

    this::currentJob.isInitialized