1

I do have a enum class in kotlin in which I have to sort them differently based on a input parameters.

As of now, I have this class defined

enum class ProductItem constructor( val color, val price, val position ){ SHOES("red", "$", 2) CAR("blue", "$$$$$", 1) BOAT("green", "$$$$$$$$$$$$$", 3) } 

As of now using a simplify code like this:

it.sortedBy { it.ProductItem?.position }) 

I was expecting that the list of enum returned will be sorted in ascending order and show: CAR, SHOES and BOAT but it still shows SHOES, CAR, BOAT. It looks like the params position is not took into account. Any idea how to use the params position to sort the list of enum

Thanks

3
  • Can you explain this a bit more please? What should be the logic for different sorting based on different parameter values (e.g. State = CA vs State = LO)? And how do these state values relate to the enum values? Commented Nov 2, 2018 at 8:11
  • Hi @YoniGibbs I have update the description to a much simpler problem Commented Nov 5, 2018 at 7:28
  • I'm not sure what it.ProductItem?.position does... Is ProductItem here a property? Can you please provide a main function that demonstrates the problem. (Also your enum code does not compile.) Commented Nov 5, 2018 at 8:03

1 Answer 1

2

From the look of your code I suspect you have some class (e.g. Order) which has an optional property called ProductItem, which returns a ProductItem enum value. And you then have a list or array of these Order objects, which you want to sort by the position of the associated ProductItem. Is that correct?

If so, here's some code below which shows how the list of orders can be sorted...

enum class ProductItem constructor( val color: String, val price: String, val position: Int ) { SHOES("red", "$", 2), CAR("blue", "$$$$$", 1), BOAT("green", "$$$$$$$$$$$$$", 3) } data class Order(val ProductItem: ProductItem? = null) val orders = listOf(Order(ProductItem.SHOES), Order(ProductItem.CAR), Order(ProductItem.BOAT)) val sortedOrders = orders.sortedBy { it.ProductItem?.position } 

Does that give you what you want?

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.