6

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

2
  • Have you tried using 'by lazy {}' to perform a kind of lateinit on the variable? val c:Int by lazy { ... } Commented Oct 24, 2018 at 8:40
  • how about using lateinit and initializing the variable in init{} Commented Oct 24, 2018 at 8:53

2 Answers 2

14

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.