2016-11-08 50 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() 
    } 
}