Martin
Martin

Reputation: 2904

How to create variable in Kotlin without initialization?

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).

Upvotes: 5

Views: 23607

Answers (2)

Hanna
Hanna

Reputation: 71

If you need to get your UI element in Kotlin, you do not need to create variable and initialise it by using findViewById anymore (though you can). Use kotlin view binding, which works pretty well.

https://kotlinlang.org/docs/tutorials/android-plugin.html#view-binding

Upvotes: 0

Tim
Tim

Reputation: 43314

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.

Upvotes: 13

Related Questions