当出现问题如下Out-projected type 'BindingCommand< * >?' prohibits the use of 'public final fun execute(parameter: T)
中文翻译过来大致意思是:输出投影类型“BindingCommand< * >?”禁止使用“public final fun execute(parameter:T)”
前提BindingCommand只是我定义的一个普通泛型类:
class BindingCommand<T> {
//public final 是默认前缀,有没有都一样,只是为了方便前文理解加上的
public final fun execute(parameter: T) {
//TODO everythings
}
}
因为Kotlin星形投影不等同于Java的原始类型。BindingCommand中的星号(*)表示您可以安全地从BindingCommand中读取值,但不能安全地向列表中写入值,因为列表中的值都是一些未知类型(例如Person、String、Number?,或者有Any?)。它和MutableList<out Any?>是一样的。
相反,如果使用<Any?>意味着您可以从列表中读取和写入任何值。值可以是相同类型(例如Person)或混合类型(例如Person和String),这就符合了Java里泛型的定义。
问题代码如下:
@BindingAdapter(value = ["currentView"], requireAll = false)
fun replyCurrentView(
currentView: View?,
bindingCommand: BindingCommand<*>?
) {
bindingCommand?.execute(currentView)//此处会报错
}
解决方案如下:
@BindingAdapter(value = ["currentView"], requireAll = false)
fun replyCurrentView(
currentView: View?,
bindingCommand: BindingCommand<Any?>?
) {
bindingCommand?.execute(currentView)
}
网友评论