https://kotlinlang.org logo
#getting-started
Title
# getting-started
d

Daniele B

08/15/2020, 9:07 PM
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

Devil Ster 1

08/15/2020, 10:13 PM
what if reorder chain? Add property to MyNewObject (calculatedField) and then sort by this property?
p

phldavies

08/15/2020, 10:23 PM
Or map to Pair<MyObj, SortVal> then sort on it.second?
n

nanodeath

08/15/2020, 10:23 PM
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

Daniele B

08/15/2020, 11:24 PM
@nanodeath thanks!
e

ephemient

08/16/2020, 5:27 AM
d

Daniele B

08/16/2020, 11:19 AM
@ephemient very interesting. Thanks!