Add non-null min() function for number arrays

Right now, to get the minimum (or maximum) of an IntArray, you can use arr.minOrNull() which, as the name suggests, can return null (if the array has no elements). However, when we are certain an array is not null, getting the minimum looks kinda ugly:

val min = arr.minOrNull()!!;

It would be way nicer to have a min() function that throws if the array is empty. Not having this is also inconsistent with the fact that there is no averageOrNull() function, but there is the average() function which does indeed throw an exception if the array is null.

Now, there is a min() function (which is not only deprecated, but using it throws an actual compile error if used, which I think is a neat feature) which also returns a nullable type. Are there already some plans of replacing this with a non-null returning min function?

It is still far from perfect, but alternatively you can use: minOf { it }. At least it doesn’t mention anything about nulls and it throws NoSuchElementException instead of NPE.

Yes, we plan to reintroduce min with non-nullable return type in Kotlin 1.7.

2 Likes