Kotlin Android: Property delegate must have a 'getValue(DashViewModel, KProperty*>)' method
Asked Answered
A

1

19

I am trying to follow the official Android guide for ViewModels in Kotlin. I literally copy pasted the easiest official example but the syntax seems to be illegal.

This section causes the problem:

private val users: MutableLiveData<List<User>> by lazy {
    MutableLiveData().also {
        loadUsers()
    }
}

The preview gives me this error:

Property delegate must have a 'getValue(DashViewModel, KProperty*>)' method. None of the following functions is suitable.

And if I want to launch the App I get this error:

Type inference failed: Not enough information to infer parameter T in constructor MutableLiveData<T : Any!>()
Please specify it explicitly.

I dont understand those two errors and other questions with the same error seem to have been caused by something different. My guess is that the MutableLiveData().also causes the problem but I do not know why. This is quite odd considering that this is an official example.

Activator answered 11/7, 2020 at 21:54 Comment(0)
T
22

It does not appear that you declared a User class.

The second problem is yet another documentation bug, and you need to provide the type in the MutableLiveData constructor call.

So, this works:

package com.commonsware.myapplication

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel

class User

class MainViewModel : ViewModel() {
  private val users: MutableLiveData<List<User>> by lazy {
    MutableLiveData<List<User>>().also {
      loadUsers()
    }
  }

  fun getUsers(): LiveData<List<User>> {
    return users
  }

  private fun loadUsers() {
    // Do an asynchronous operation to fetch users.
  }
}

This is quite odd considering that this is an official example.

In general, consider them an illustration of a technique, not necessarily something that you would copy and paste into a project.

Towandatoward answered 11/7, 2020 at 22:20 Comment(2)
It's not optimistic to expect docs to be correct (this speaks more to Google's docs quality than the poster having unreasonable expectations). Let's be nice to folks who have questions, since that is, after all, the whole point of Stack OverflowWhacking
Google docs are very lacking compared to Oracle's. You can pretty much copy paste from Oracle's docs to your heart's content when you are using Java and get working examples that you can mutate to you liking. It was such a let down to find out how bare Google's developer guides are, and even more, their documentation. Trying to find out what some public methods do, and what cryptic undocumented error messages mean is impossible without diving into Android source code, and even then it is such a time sucker.Walkthrough

© 2022 - 2024 — McMap. All rights reserved.