在我的Android项目的ViewModel中:
import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
class MainViewModel(application: Application) : AndroidViewModel(application) {
private var waitressCallContainerHeights = MutableLiveData<Pair<Int, Int>>()
fun init() {
waitressCallContainerHeights.value.first = 200
}
}
但是在这一行中我得到了编译错误:
waitressCallContainerHeights.value.first = 200
Val cannot be reassigned
我想有趣地init
答案 0 :(得分:6)
尽管liveData是可变的,但是Pair本身不是。您需要做:
waitressCallContainerHeights.value = Pair(200,300/* for example */)
答案 1 :(得分:1)
您还可以使用apply
在声明本身上初始化变量,如下所示:
private var waitressCallContainerHeights = MutableLiveData<Pair<Int, Int>>().apply { value = Pair(200, 300) }