Kotlin Android:属性委托必须具有“ getValue(DashViewModel,KProperty *>)”方法

时间:2020-07-11 21:54:38

标签: android kotlin android-livedata kotlin-extension

我正在尝试遵循Kotlin中适用于ViewModels的官方Android指南。 我从字面上复制了最简单的official example,但语法似乎是非法的。

此部分会导致问题:

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

预览给我这个错误:

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

如果我要启动该应用程序,则会出现此错误:

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

我不明白这两个错误以及其他具有相同错误的问题似乎是由不同的原因引起的。我的猜测是MutableLiveData().also会导致问题,但我不知道为什么。考虑到这是一个官方示例,这很奇怪。

1 个答案:

答案 0 :(得分:9)

您的第一个问题是您没有声明User类。

第二个问题是yet another documentation bug,您需要在MutableLiveData构造函数调用中提供类型。

所以,这可行:

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

考虑到这是一个官方示例,这很奇怪。

对于这些示例,您非常乐观。通常,将它们视为一种技术的说明,不一定是您将复制并粘贴到项目中的内容。