Kotlin 中的 min 和 minOf 有什么区别?
What is the difference between min and minOf in Kotlin?
在我的遗留代码中我有这个:
java.lang.Math.min(a, b)
我想用 Kotlin 等效项替换它,但我有点困惑应该使用哪个。我找到了这两个:
kotlin.math.min(a,b)
kotlin.comparisons.minOf(a,b)
正如我所注意到的,它们都在内部调用 Math.min
。我想念的它们之间有什么区别吗?其中之一是将来使用的首选吗?
Kotlin kotlin.math.min(a,b) 采用 Int
、Double
、Float
、Long
等具体类型并进行数学比较。
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 关于 class。
现在用哪个?
如您所见,kotlin.comparisons.minOf(a,b)
是比 kotlin.math.min(a,b)
更通用的实现。如果您使用的是数字类型,那么使用哪种并不重要,因为正如您已经指出的那样,两者都是使用 Math.min(a, b)
实现的。
在我的遗留代码中我有这个:
java.lang.Math.min(a, b)
我想用 Kotlin 等效项替换它,但我有点困惑应该使用哪个。我找到了这两个:
kotlin.math.min(a,b)
kotlin.comparisons.minOf(a,b)
正如我所注意到的,它们都在内部调用 Math.min
。我想念的它们之间有什么区别吗?其中之一是将来使用的首选吗?
Kotlin kotlin.math.min(a,b) 采用 Int
、Double
、Float
、Long
等具体类型并进行数学比较。
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 关于 class。
现在用哪个?
如您所见,kotlin.comparisons.minOf(a,b)
是比 kotlin.math.min(a,b)
更通用的实现。如果您使用的是数字类型,那么使用哪种并不重要,因为正如您已经指出的那样,两者都是使用 Math.min(a, b)
实现的。