0

I'm sorting a list of Pair<Int, String> with this:

list.sortedWith(Comparator.comparingInt<Pair<String, Int>> { it.second }
    .thenComparing { it -> it.first })

It seems a bit odd to have to specify { it -> so is there something more Kotlin-ish I should be using?


Edit: Sorry, I got lost while asking the question: while I did want to know the answers below, what I suppose I was really curious about was why I can't leave out the it ->:

This compiles:

var c = Comparator
    .comparingInt<Pair<String, Int>> { it.second }
    .thenComparing { it -> it.first }

This complains with 'unresolved reference it':

 var c = Comparator
     .comparingInt<Pair<String, Int>> { it.second }
     .thenComparing { it.first }
Tim Baverstock
  • 415
  • 4
  • 11
  • You can always omit `it ->` in a lambda when the type can be inferred, because `it` is an implicit parameter for single-parameter lambdas: `{ it.first }` – hotkey Oct 16 '18 at 09:55
  • Yeah, I tried removing the it -> and IntelliJ didn't like that. I suppose that was my real question - why omitting 'it ->' doesn't work. – Tim Baverstock Oct 18 '18 at 07:45

1 Answers1

2

I guess this is what you're looking for:

sortedWith(compareBy({ it.first }, {it.second})
s1m0nw1
  • 76,759
  • 17
  • 167
  • 196
  • It certainly is, but I changed my question a bit: I forgot that what was really bugging me was why I needed 'it ->' in the second clause of the comparator, and what I should have been doing not to need it - whether there's a way to have Comparator.xxxx { it.first }.yyyy { it.second }. – Tim Baverstock Oct 18 '18 at 08:00