13

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 3

22

Another observation is that sortedBy returns a sorted copy of the list. If you want to sort your mutable list in place, you should use sortBy function:

tokens.sortBy { it.position.first } 
// tokens is sorted now
Sign up to request clarification or add additional context in comments.

1 Comment

Also, use a sortByDescending for the reversed sort!
3

The position is a parameter rather than a property, to make it to a property on the primary constructor by val/var keyword, for example:

//makes the parameter to a property by `val` keyword---v
class Token(val type: TokenType,  val value: String,  val position:IntRange = 0..0)

THEN you can sort your Tokens by the position, for example:

tokens.sortedBy { it.position.first }

2 Comments

oh, dumb mistake. Thank you :)
@Rechunk Not at all. it is my pleasure, :)
3

try with sortBy method,

val result = tokens.sortBy { it.position } 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.