📜  Kotlin 中的可比接口

📅  最后修改于: 2022-05-13 01:54:42.507000             🧑  作者: Mango

Kotlin 中的可比接口

由于Kotlin为程序员提供了根据类定义新类型的方法,因此必须有一种方法来比较这些类的实例。与Java中一样,Comparable 接口提供了一个compareTo()函数来比较两个对象。 Kotlin 通过Comparable 接口提供了这一点。但是,它也提供了某些扩展功能,从而提供了更多的功能。 Kotlin 还提供了一个额外的优势,即实现 Comparable 接口的实例可以使用关系运算符进行比较。

职能 -

相比于() -
此函数将调用对象与传递的对象进行比较。如果两者相等,则返回,如果传递的对象更大,则返回负数,否则返回数。

abstract operator fun compareTo(other: T): Int

扩展功能 –

coerceAtLeast() –
该函数检查调用对象是否大于某个最小对象。如果大于则返回当前对象,否则返回最小对象

fun  T.coerceAtLeast(minimumValue: T): T

coerceAtMost() –
此函数检查调用对象是否小于给定的最大对象。如果它较小,则返回当前对象,否则返回最大对象。

fun  T.coerceAtMost(maximumValue: T): T

强制输入() -
该函数检查调用对象是否在某个最小值最大值之内。如果对象在范围内,则返回对象,否则如果对象小于最小值,则返回最小值,否则返回最大值。

fun  T.coerceIn(
    minimumValue: T?, 
    maximumValue: T?
): T

演示 Comparable 接口的示例 -

class Rectangle(val length: Int, val breadth: Int): Comparable{
    override fun compareTo(other: Rectangle): Int {
        val area1 = length * breadth
        val area2 = other.length * other.breadth
  
        // Comparing two rectangles on the basis of area
        if(area1 == area2){
            return 0;
        }else if(area1 < area2){
            return -1;
        }
        return 1;
    }
}
  
fun main(){
    var obj1 = Rectangle(5,5)
    var obj2 = Rectangle(4,4)
    var min = Rectangle(2,2)
    var max = Rectangle(9,9)
  
    // Using relational operator compare two rectangles
    println("Is rectangle one greater than equal"+
                " to rectangle two? ${obj1>obj2}")
    println("Is rectangle one greater than the " +
            "minimum sized rectangle? ${obj1.coerceAtLeast(min) == obj1} ")
  
    obj2 = Rectangle(10,10)
    println("Is rectangle two smaller than " +
            "the maximum sized rectangle? ${obj2.coerceAtMost(max) == obj2}")
  
    println("Is rectangle one within " +
            "the bounds? ${obj1.coerceIn(min,max) == obj1}")
}

输出:

Is rectangle one greater than equal to rectangle two? true
Is rectangle one greater than the minimum sized rectangle? true 
Is rectangle two smaller than the maximum sized rectangle? false
Is rectangle one within the bounds? true

范围到() -
此函数检查值是否在范围内。如果在范围内未找到值,则返回 false,否则返回 true。这里的数字是根据 IEEE-754 标准进行比较的。

operator fun > T.rangeTo(
    that: T
): ClosedRange

Kotlin 程序使用 rangeTo()函数——

fun main(args : Array) {
    val range = 1..1000
    println(range)
  
    println("Is 55 within the range? ${55 in range}") // true
    println("Is 100000 within the range? ${100000 in range}") // false
}

输出:

1..1000
Is 55 within the range? true
Is 100000 within the range? false