is it possible in kotlin to retrieve a value previ...
# getting-started
d
is it possible in kotlin to retrieve a value previously calculated for sorting, so that I don’t have to calculate it twice?
Copy code
myList
.sortedBy { val calculatedField = it.fieldA / it.fieldB }
.mapIndexed { index, elem -> MyNewObject(
    _index = index+2, 
    _value = calculatedField,
    _fieldA = fieldA.toInt()
    _fieldB= fieldB.toInt()
  )
}
unfortunately this code doesn’t work: I can’t access calculatedField from inside the map function
d
what if reorder chain? Add property to MyNewObject (calculatedField) and then sort by this property?
p
Or map to Pair<MyObj, SortVal> then sort on it.second?
n
Copy code
myList
  .asSequence()
  .map { SortableThing(it, calculatedField = it.fieldA / it.fieldB) }
  .sortedBy { it.calculatedField }
  .mapIndexed { /* etc */ }
  .toList()
Pair
would also do it
Copy code
myList
  .asSequence()
  .map { it to (it.fieldA / it.fieldB) }
  .sortedBy { (_, cf) -> cf }
  .mapIndexed { idx, (l, _) -> /* etc */ }
  .toList()
1
d
@nanodeath thanks!
e
d
@ephemient very interesting. Thanks!