viewModel() unresolved reference

I have followed the book word for word (right. If I had I wouldn’t have this problem) as best as I can see. I included the ViewModel dependency in app/build.gradle but the version number is up from 2.4.1 to 2.5.1 and added the activity dependency, vs 1.4.0 now 1.5.1. I added a new class for the view model as described in the book. I added the code to MainActivity.kt as in the book but this line:
private var quizViewModel: QuizViewModel by viewModels() has a problem recognizing viewModels(). I imported andoidx.activity.viewModels and now it tells me this:
Type ‘Lazy<TypeVariable(VM)>’ has no method ‘setValue(MainActivity, KProperty<*>, QuizViewModel)’ and thus it cannot serve as a delegate for var (read-write property) and an abundance of other text. Help?

You want to make quizViewModel a val instead of a var. If you remember from Kotlin, there are two different ways to define a class property, either val or var. val is read-only while var is read-write. The viewModels() function is a property delegate, which allows you to delegate (hence the name) how a property is created/accessed. It does a lot of setup and configuration to make sure that your QuizViewModel works like how it is supposed to. The viewModels() property delegate function works only with read-only properties, so you have to define quizViewModel as a val.

That error message can be pretty inscrutable for new developers. Hope this helped.

Well. That was easy. And I’m not a new developer. AND I used to teach development on the college level. Finding this sort of single character problem was my specialty. Now, years later and a prescription or two later, my eyes just don’t do what they use to do. Thanks for seeing it for me.


1 Like