美文网首页
Kotlin Out-projected type 'Bindi

Kotlin Out-projected type 'Bindi

作者: 薛之东_HankGreen | 来源:发表于2020-03-07 18:17 被阅读0次

    当出现问题如下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)
        }
    

    相关文章

      网友评论

          本文标题:Kotlin Out-projected type 'Bindi

          本文链接:https://www.haomeiwen.com/subject/baqhdhtx.html