0

I know my approach to accomplish what I have tried to is not the perfect way to do it. I tried to use when statement but I couldn't do it. How can I convert my code with when statement instead of if...else? Which option is perfect to use in such scenarios?

            if(stock>10.toBigDecimal()){
                holder.itemView.tv_dashboard_item_stock.text = "In Stock"
            }else if(stock>5.toBigDecimal()){
                holder.itemView.tv_dashboard_item_stock.text = "Only $stock left"
            }else{
                holder.itemView.tv_dashboard_item_stock.setTextColor(Color.MAGENTA)
                holder.itemView.tv_dashboard_item_stock.text = "Enquire"

                holder.itemView.tv_dashboard_item_stock.setOnClickListener {
                    Toast.makeText(context,"You clicked",Toast.LENGTH_LONG).show()
                }
            }
Codist
  • 737
  • 8
  • 23

1 Answers1

1
when {
    stock > 10.toBigDecimal() -> holder.itemView.tv_dashboard_item_stock.text = "In Stock"
    stock > 5.toBigDecimal() -> holder.itemView.tv_dashboard_item_stock.text = "Only $stock left"
    else -> {
        holder.itemView.tv_dashboard_item_stock.setTextColor(Color.MAGENTA)
        holder.itemView.tv_dashboard_item_stock.text = "Enquire"
        holder.itemView.tv_dashboard_item_stock.setOnClickListener {
            Toast.makeText(context,"You clicked",Toast.LENGTH_LONG).show()
        }
    }
}
 

https://kotlinlang.org/docs/control-flow.html#when-expression

Héctor
  • 24,444
  • 35
  • 132
  • 243
  • There is one problem here that I had with the if statement too. I thought the issue will get resolved if I change to `when`. The issue is that the text colour of the last item in the recyclerview also get changed to Color.MAGENTA. – Codist Jun 22 '21 at 10:18
  • Can you also tell me how can I use #FF6D00, which is in my colors.xml instead of Color.MAGENTA? – Codist Jun 22 '21 at 10:20
  • May this helps: https://stackoverflow.com/questions/5271387/how-can-i-get-color-int-from-color-resource – Héctor Jun 22 '21 at 10:21
  • Unfortunately, the link didn't solve both the issues. – Codist Jun 22 '21 at 10:44