What is the difference between min and minOf in Kotlin?

Viewed 1323

In my legacy code I have this:

java.lang.Math.min(a, b)

I'd like to replace it with Kotlin equivalent, but I'm a little confused which one should I use. I found these two:

kotlin.math.min(a,b)
kotlin.comparisons.minOf(a,b)

As I noticed, both of them internally call Math.min. Is there any difference between them that I miss? Is one of them preferred for future use?

1 Answers

Kotlin kotlin.math.min(a,b) takes concrete types like Int, Double, Float, Long and compares them mathematically.

Kotlin kotlin.comparisons fun <T : Comparable<T>> minOf(a: T, b: T): T takes a generic type T, that extends the interface Comparable<T>. This can be used in collections to sort them, based on the implementation of Comparable on that class.

Which to use now?

As you see, kotlin.comparisons.minOf(a,b) is a more generic implementation than kotlin.math.min(a,b). If you are using number types it does not really matter which to use, as both are implemented with Math.min(a, b) as you already pointed out.

Related