Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

272
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda