我正试着按照官方的Android指南在Kotlin中使用ViewModels. 我从字面上复制粘贴了最简单的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.

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.

我不明白这两个错误和其他同样错误的问题似乎是由不同的原因造成的.我猜是MutableLiveData().also导致了这个问题,但我不知道为什么.考虑到这是一个官方的例子,这很奇怪.

推荐答案

It does not appear that you declared a User class.

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

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

考虑到这是一个官方的例子,这相当奇怪.

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

Kotlin相关问答推荐

何时使用figureEach

在调用父构造函数之前重写类属性

相当于roomdb中的DateTime Bigint列的是什么

当我通过媒体通知更改音乐时不要更新我的 UI

使用事务时未调用 Kafka ConsumerInterceptor onCommit

为什么 KFunction2 在 Kotlin 中不是可表示类型?

Kotlin 使用迭代索引过滤 lambda 数组

OnClickListener 未在 ConstraintLayout 上触发

Kotlin:内部类如何访问在外部类中声明为参数的变量?

无法删除部分子项.这可能是因为进程打开了文件或将其工作目录设置在目标目录中

将 Kotlin 类属性设置器作为函数引用

变量后的Android问号

Dagger2 Qualifier 不适用于 Kotlin?

编译错误:-Xcoroutines has no effect: coroutines are enabled anyway in 1.3 and beyond

修改扩展函数中的this

Kotlin中的Memoization功能

具有泛型param的Kotlin抽象类和使用类型param的方法

什么是 Kotlin 等价于 Class<?>

Android studio 4.0 新更新版本说 Kotlin 与这个新版本不兼容

从 java 活动 *.java 启动 kotlin 活动 *.kt?