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 } }
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.
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".
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.
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.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With