Kek
Kek

Reputation: 381

Android Studio warns that value cannot be null, however, it can. Is it something wrong with compiler?

I'm using the latest version of Android Studio. When coding today, I found an interesting warning it gave me. So on line 45, I've got a code

categoryAdapter?.notifyDataSetChanged()

It says that categoryAdapter cannot be null, however, it can, as clearly seen on the second screenshot.

enter image description here enter image description here

The setter on categories is called before categoryAdapter was initialised and thus it's null (what makes sense), as seen on the 3rd screenshot (categoryAdapter is initialised on the line 87). Is it a bug in compiler?

enter image description here

Upvotes: 0

Views: 267

Answers (2)

Alexey Romanov
Alexey Romanov

Reputation: 170805

It's a design issue, but I don't see any better alternative to what the compiler currently does.

When method bodies are checked, it's basically assumed the instance is fully constructed. Otherwise any access to categoryAdapter from any method would need to be marked with ? just in case you call this method in the constructor before initializing categoryAdapter.

Maybe the compiler could treat methods called in init blocks specially, at least non-open ones.

Upvotes: 1

LukeWaggoner
LukeWaggoner

Reputation: 8909

You don't define CategoryAdapter as nullable. In order for it to be nullable you have to give it a type of CategoryAdapter?. I suspect the reason it's not complaining that you haven't initialized it is because you've marked it with @get:Bindable.

I suggest that it may be better to make the variable a lateinit var rather than a non-nullable val. Vals are immutable so you won't be able to assign it a value anyway.

Upvotes: 1

Related Questions