Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create variable in Kotlin without initialization?

Tags:

android

kotlin

This is simple question. In Java you can create String variable or couple of variables without adding any value to it. This is used at start of the class before onCreate() is called in Activity. I've used lateinit property in Kotlin to achieve that, but now I have a problem with changing visibility of RecyclerView. It will throw exception "lateinit property recyclerView has not been initialized".

Is there any way how to know if property is initialized? This is called at start of the parent activity in Fragment (hide recyclerView and show ProgressBar till data are binded to recyclerView).

like image 590
martin1337 Avatar asked Sep 01 '26 09:09

martin1337


1 Answers

In Java you can create String variable or couple of variables without adding any value to it

Actually in that case it is implicitly declared null. Kotlin does not do that, because of its nullability mechanism. You must explicitly declare a variable nullable to allow null:

var str: String // does not work
var str: String? // does not work
var str: String? = null // works

Also see this answer.

Your other option indeed is to mark it lateinit:

lateinit var str: String // works

If you need to make a check to see if it is initialized before using it, you use

if (::str.isInitialized)

But really you should avoid this check and just make sure it is initialized before using it.

like image 173
Tim Avatar answered Sep 02 '26 23:09

Tim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!