2016-11-08 48 views
1

我已经过去了一个lambda,它有一个未知类型的变量,并且在when..is条件中,该变量不能智能地转换为is条件中的类型。 ..它给出了这是不可能的,因为变量是一个公共Api,有没有解决这个问题的方法?lambda kotlin变通方法中的智能铸造变量

enter image description here

+1

请添加代码的文本形式剪断,以便它可以复制-pasted。我不得不重新键入你的代码来回答你的问题,这并不令人愉快。 – voddan

回答

1

我发现这是定义VAL等于想要的变量并使用它是这样的...

enter image description here

0

做的另一种方式是一个简单的解决方法使投自己:

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

当你有多个孩子的对象时,它会变得刺激,所以我认为 – Seaskyways

2

您可以创建一个更方便的扩展onBind˚F油膏具有itemview等传递给拉姆达而不是接收的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() 
    } 
}