Variable initialisation as non-null in android framework


Hello. I recently started to learn Kotlin (well not that recently, more like half a year of 8 hours coding everyday) and i somehow feel like there could be a better option for variables initialisation that cannot hold null values, but cannot be ‘visibly’ initialised. For instance, in android framework, almost everything we code has an implicit class that has no constructor available (activity, fragment, service, dialogfragment), which means the init block to initialise variable won’t work either.

So for instance, i have to declare a couple of variable within an activity. I end up using lazy, or Delegates.notNull(), but i find this solution not right at all. I may be a bit paranoid, but simple variables that are, for instance, initialised in onCreate must be declared like that. Even a simple Int that we are reading from a intent, must be wrapped in a class (Delegates.notNull). Isn’t it any other way of accomplish this? Like the possibility to write, for example,
val someVariable: Int, and then initialise in onCreate without the compiler always checking for ‘variable not initialised’ stuff. It will obviously be up to the user to make sure the variables are initialised before accessed, but that’s how java is anyway


Are you familiar with the lateinit modifier?


yes i am thank you for your fast reply. The language is great and i love it. I knew about lateinit, but always thought it as a ‘dependency-injection stuff’. Maybe that what im looking for. Can you provide me a link or something that explains how lateinit feature is implemented? I know how lazy and Delegates work, cause i can see how it is coded, but not for lateinit. Thank you in advanced


There is no special implementation behind it. A lateinit var is a regular non-final field which Kotlin initializes with null by default, and throws a special exception if you access it before null has been replaced with a different value.


Ok. Guess that is exactly what i was looking for then. Primitive types can’t be used with lateinit, but they also have their default values so problem solved. Thank you for your help and work man:p
Really appreciate this wonderful language. Sometimes i have to write Java at work and something just not feels right.