Codist
Codist

Reputation: 769

How to use when statement in Kotlin?

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()
                }
            }

Upvotes: 0

Views: 62

Answers (1)

Héctor
Héctor

Reputation: 26034

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

Upvotes: 1

Related Questions