【问题标题】:Smart cast variable in lambda kotlin workaroundlambda kotlin 解决方法中的智能转换变量
【发布时间】:2016-11-08 22:46:26
【问题描述】:

我今天已经过了一个 lambda,它有一个未知类型的变量,并且在 when..is 条件内,变量不能智能转换为 is 条件中的类型......它给出了它是不可能,因为变量是 Public Api ,有解决方法吗?

【问题讨论】:

  • 请在文本表单中添加您的代码,以便可以复制粘贴。我不得不重新输入你的代码来回答你的问题,这不是那么令人愉快。

标签: android variables lambda casting kotlin


【解决方案1】:

您可以创建一个更方便的onBind 扩展函数,将itemview 等传递给lambda,而不是接收ItemViewTypePosition

inline fun LastAdapter.Builder.onBind(crossinline f: (item: Any, view: View, type: Int, position: Int) -> Unit): LastAdapter.Builder {
    return onBindListener(object : OnBindListener {
        override fun onBind(item: Any, view: View, type: Int, position: Int) {
            f(item, view, type, position)
        }
    })
}

用法:

builder.onBind { item, view, type, position ->
    when (item) {
        is Product -> view.number_sold.text = item.price.toString()
    }
}

【讨论】:

    【解决方案2】:

    我找到了一个简单的解决方法,它定义一个 val 来等于想要的变量,然后像这样使用它......

    【讨论】:

      【解决方案3】:

      另一种方法是自己制作演员表:

      .onBind {
          when(item) {
              is Product -> view.number_sold_text = (item as Product).price.toString()
          }
      }
      

      【讨论】:

      • 当你有多个子对象时会变得很烦人,所以我同意这个
      猜你喜欢
      • 1970-01-01
      • 2017-10-20
      • 2020-11-22
      • 1970-01-01
      • 2018-04-14
      • 1970-01-01
      • 2018-02-07
      • 1970-01-01
      • 2013-11-29
      相关资源
      最近更新 更多