Kotlin Android: 属性 委托必须有一个 'getValue(DashViewModel, KProperty*>)' 方法
Kotlin Android: Property delegate must have a 'getValue(DashViewModel, KProperty*>)' method
我正在尝试遵循 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
导致了问题,但我不知道为什么。考虑到这是官方示例,这很奇怪。
您似乎没有声明 User
class。
第二个问题是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.
}
}
This is quite odd considering that this is an official example.
一般来说,将它们视为一种技术的说明,不一定是您要复制并粘贴到项目中的东西。
我正在尝试遵循 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
导致了问题,但我不知道为什么。考虑到这是官方示例,这很奇怪。
您似乎没有声明 User
class。
第二个问题是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.
}
}
This is quite odd considering that this is an official example.
一般来说,将它们视为一种技术的说明,不一定是您要复制并粘贴到项目中的东西。