Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a "lateinit" variable has been initialized?

Tags:

kotlin

I wonder if there is a way to check if a lateinit variable has been initialized. For example:

class Foo() {      private lateinit var myFile: File      fun bar(path: String?) {         path?.let { myFile = File(it) }     }      fun bar2() {         myFile.whateverMethod()         // May crash since I don't know whether myFile has been initialized     } } 
like image 760
Mathew Hany Avatar asked Jun 03 '16 15:06

Mathew Hany


People also ask

How do you check Lateinit variable is initialized or not?

You can check if the lateinit variable has been initialized or not before using it with the help of isInitialized() method. This method will return true if the lateinit property has been initialized otherwise it will return false.

How do you initialize Lateinit property?

In order to create a "lateInit" variable, we just need to add the keyword "lateInit" as an access modifier of that variable. Following are a set of conditions that need to be followed in order to use "lateInit" in Kotlin. Use "lateInit" with a mutable variable. That means, we need to use "var" keyword with "lateInit".

What happens when a field declared as Lateinit is accessed before it is initialized?

Accessing a lateinit property before it has been initialized throws a special exception that clearly identifies the property being accessed and the fact that it hasn't been initialized.

Is Lateinit null?

While using Lateinit , the variable can't be of the null type. Lateinit cannot be used for non-primitive datatypes, i.e., Long and int. If you try accessing Lateinit variables without initializing, it will throw an exception stating that it is not initialized or properly being accessed.


1 Answers

There is a lateinit improvement in Kotlin 1.2 that allows to check the initialization state of lateinit variable directly:

lateinit var file: File      if (this::file.isInitialized) { ... } 

See the annoucement on JetBrains blog or the KEEP proposal.

UPDATE: Kotlin 1.2 has been released. You can find lateinit enhancements here:

  • Checking whether a lateinit var is initialized
  • Lateinit top-level properties and local variables
like image 122
xsveda Avatar answered Oct 18 '22 22:10

xsveda