Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

271
Views
Check if a local lateinit variable is initialized

Member lateinit variables initialization can be checked with:

class MyClass {
    lateinit var foo: Any
    ...
    fun doSomething() {
        if (::foo.isInitialized) {
           // Use foo
        }
    }
}

However this syntax doesn't work for local lateinit variables. Lint reports the error: "References to variables aren't supported yet". There should logically be a way to do that since lateinit variables are null internally when uninitialized.

Is there a way to check if local variables are initialized?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

The code you show in your question is actually fine in Kotlin 1.2 and beyond, since foo is an instance variable, not a local variable. The error message you report and mentioned in Alexey's comment (Unsupported [References to variables aren't supported yet]) can be triggered by a true local variable, for example in the doSomethingElse method below.

class MyClass {
    lateinit var foo: Any

    fun doSomething() {
        if (::foo.isInitialized) {  // this is fine to use in Kotlin 1.2+
           // Use foo
        }
    }
    fun doSomethingElse() {
        lateinit var bar: Any

        if (::bar.isInitialized) {  // this is currently unsupported (see link in Alexey's comment.
            // Use bar 
        }

    }

}

So it seems like this is currently unsupported. The only place that comes to mind where a lateinit local would be used would be if the local is variable captured in a lambda?

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!