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:-

9

There are a few scenarios in which this is particularly useful, for example:

  • Variables that are initialized in LIFECYCLE methods in Android;
  • Using Dagger for DI: injected class variables are initialized outside of the constructor and independently;
  • Setup for unit tests: in a @Before - annotated function, test environment variables are initialized;
  • Annotations in Spring Boot (for example, @Autowired).


Discussion

No Comment Found