InterviewSolution
| 1. |
What do you understand about lateinit in Kotlin? When would you consider using it? |
|
Answer» lateinit is an abbreviation for LATE INITIATION. If you don't want to initialize a variable in the constructor and instead want to do it later, and you can guarantee the initialization before using it, use the lateinit keyword to declare that variable. It won't start allocating memory until it's been initialized. Lateinit cannot be USED for primitive type attributes like Int, Long, and so on. Because the lateinit variable will be initialized later, you cannot use val. When a lateinit property is ACCESSED before it has been initialized, a special exception is thrown that explicitly identifies the property and the fact that it hasn't been initialized. For example, // KOTLINlateinit var test: Stringfun testFunction() { test = "Interview" println("The length of string is "+test.length) test = "Bit"}When the testFunction is called, we get the following output:- 9There are a few scenarios in which this is particularly useful, for example:
|
|