Currently, if a collection has more than one instance of the largest element, max()
, maxBy()
and, maxWith()
returns the first one found (like min()
, minBy()
and, minWith()
). I would argue that the right behavior should be to return the last largest element instead of the first one (but Alex Stepanov does a better job explaining why ).
Even one of the example problems provided on “Try Kotlin” seems to support this. On this problem, the code:
fun indexOfMax(a: IntArray): Int? {
return a.withIndex().maxBy { it.value }?.index
}
won’t pass all the tests, failing on these two cases:
indexOfMax(Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE) is 0, not 2.
indexOfMax(Integer.MIN_VALUE, Integer.MIN_VALUE, Integer.MIN_VALUE) is 0, not 2.
This can be easily fixed replacing <
with <=
on the corresponding templates for max
, maxBy
and maxWith
defined in kotlin/libraries/tools/kotlin-stdlib-gen/src/templates/Aggregates.kt
.
Is that an oversight or is on purpose?
Should I create a PR for this?