Late-Initialized Properties in Kotlin

var variable : CustomClass = CustomClass() 
or
var variable : CustomClass? = null
This post was originally posted at https://agrawalsuneet.github.io/blogs/lateinit-property-in-kotlin/ and reposted on Medium on 10th Nov 2017.
variable?.someMethodCall()//orvariable!!.someMethodCall()
lateinit var variable : CustomClass
variable = CustomClass()
variable.someMethodCall()
  1. lateinit can only be used with var properties declared inside the body of class (not in the primary constructor) but not inside any method.
  2. It can only be used when the property does not have a custom getter or setter.
  3. The type of the property must be non-null, and it must not be a primitive type.
  4. 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.

--

--

https://agrawalsuneet.github.io/

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store