[英]Why do i get “useless cast” when casting MutableLiveData to LiveData?
I have an array of feedback channels because (outside of question scope) in my ViewModel
.我有一系列反馈渠道,因为(在问题范围之外)在我的
ViewModel
中。
Now, I don't want to expose my MutableLiveData
to outside my Viewmodel
.现在,我不想将我的 MutableLiveData 暴露在我的
MutableLiveData
Viewmodel
。
So, i make a private list of LiveData
objects, but compiler complains of "Useless Cast"所以,我创建了一个
LiveData
对象的私有列表,但编译器抱怨“无用的演员表”
private val _feedbackChannels = Array(10) { MutableLiveData<FeedbackEvent>() }
val feedbackChannels
get() = _feedbackChannels.map{
@Suppress("USELESS_CAST") // it is not useless as it no longer exposes the mutableLiveData
it as LiveData<*>
}
Why do I get USELESS_CAST
warning?为什么我会收到
USELESS_CAST
警告?
Compiler doesn't realize you're doing it only to force implication of property type.编译器没有意识到你这样做只是为了强制暗示属性类型。
Just specify type explicitly and you'll be able to drop the cast entirely.只需明确指定类型,您就可以完全放弃演员表。 You won't even have to use map, a simple
toList()
will do:你甚至不必使用 map,一个简单的
toList()
就可以了:
private val _feedbackChannels = Array(10) { MutableLiveData<FeedbackEvent>() }
val feedbackChannels : List<LiveData<FeedbackEvent>>
get() = _feedbackChannels.toList()
Clearly the compiler doesn't understand the point of the cast.显然编译器不理解强制转换的意义。 In order to do this in a more explicit way and remove the costly
map
function, you can just upcast it like this:为了以更明确的方式执行此操作并删除昂贵的
map
function,您可以像这样向上转换它:
private val _feedbackChannels = Array(10) { MutableLiveData<FeedbackEvent>() }
val feedbackChannels: Array<out LiveData<FeedbackEvent>>
get() = _feedbackChannels
Edit编辑
If you wanted to expose a List
specifically (avoid exposing a mutable array) then you should probably just create one in the first place:如果您想专门公开一个
List
(避免公开一个可变数组),那么您可能应该首先创建一个:
private val _feedbackChannels = List(10) { MutableLiveData<FeedbackEvent>() }
val feedbackChannels: List<out LiveData<FeedbackEvent>>
get() = _feedbackChannels
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.