Home > Blockchain >  What are the differences between the maxOf() and max() methods in Kotlin?
What are the differences between the maxOf() and max() methods in Kotlin?

Time:02-02

I am a little confused by the different use-cases of the methods. I can see that one is in Kotlin.math and one in Kotlin.comparisons, so I would guess that implies maxOf() can be used with objects of user-defined classes, but is that the only differentiating factor?

CodePudding user response:

Perhaps knowing the history here can help.

In Kotlin 1.1, minOf and maxOf got added as their own separate feature. I think the idea is that you are supposed to use this in rather non-mathematical situations. After all, the example they gave was:

val list1 = listOf("a", "b")
val list2 = listOf("x", "y", "z")
val minSize = minOf(list1.size, list2.size)
val longestList = maxOf(list1, list2, compareBy { it.size })

Imagine just trying to write some readable code, putting the word "of" in there just makes the line a tad bit more English-y.

Later, in Kotlin 1.2, they added a whole lot of math constants and functions into the standard library, and called the package kotlin.math. Since min and max are also mathematical functions, they also added min and max.

This is just my opinion, but compared to minOf and maxOf, min and max would be more readable if you put them inside a more complex mathematical expression. It'd make the whole thing look more like math, rather than English.

Functionally, they behave the same, and as you said, minOf and maxOf also works for any Comparable things, or anything at all if you provide a Comparator. This is because minOf and maxOf is not strictly designed for mathematical situations, whereas min and max are.

Notice that in Kotlin 1.4, vararg versions of maxOf and minOf also got added, but not for min and max. Again this is because the mathematical min and max conventionally only take two arguments.

  • Related