Kotlin - Sort MutableList based on Object Property

Viewed 11585

I have this Token Object:

class Token(type: TokenType, value: String, position: IntRange = 0..0)

I declare a MutableList:

val tokens: MutableList<Token> = mutableListOf()

// Mutable List filled

Now I want to sort my list based on the first value of the position IntRange. I tried doing this:

tokens
          .sortedBy { it.position.first }

However, I have no access to the object after using the it keyword, so position is highlighted red.

Any suggestions?

3 Answers

try with sortBy method,

val result = tokens.sortBy { it.position } 
Related