Kotlin - 使用 .. 创建范围时会发生什么,或者它如何执行比较?

Kotlin - What happens when a range is created using .. or how it performs comparations?

我最近注意到代码重构来自:

   if (date < minDate || date > maxDate)

if (date !in minDate..maxDate) 

我主要担心的是,使用范围会在 minDatemaxDate 之间创建一个 "array" 或 所有毫秒 的列表]

我尝试研究了一些 kotlin 内部结构,但无法得到关于这种情况下会发生什么的最终答案。

据推测:

In Kotlin in checks are translated to the corresponding contains calls

根据Range class在kotlin中的实现,它不会创建列表,比较将如下进行(比较范围时调用contains),基于LongProgression class(创建于 Long 个范围)。

/**
 * A range of values of type `Long`.
 */
public class LongRange(start: Long, endInclusive: Long) : LongProgression(start, endInclusive, 1), ClosedRange<Long> {
    override val start: Long get() = first
    override val endInclusive: Long get() = last

    override fun contains(value: Long): Boolean = first <= value && value <= last

    override fun isEmpty(): Boolean = first > last

    override fun equals(other: Any?): Boolean =
        other is LongRange && (isEmpty() && other.isEmpty() ||
        first == other.first && last == other.last)

    override fun hashCode(): Int =
        if (isEmpty()) -1 else (31 * (first xor (first ushr 32)) + (last xor (last ushr 32))).toInt()

    override fun toString(): String = "$first..$last"

    companion object {
        /** An empty range of values of type Long. */
        public val EMPTY: LongRange = LongRange(1, 0)
    }
}

不,它不会创建包含每个可能值的数组(因为数组对此效率低下,即使我们确实需要存储每个值,但我们不需要)。

这是 ClosedRange 接口的源代码,.. 范围运算符将其转换为(注释已删除):

public interface ClosedRange<T: Comparable<T>> {
    public val start: T
    public val endInclusive: T    
    public fun isEmpty(): Boolean = start > endInclusive

    public operator fun contains(value: T): Boolean = 
        value >= start && value <= endInclusive
}

如您所见,它涵盖的类型 (T) 必须实现 Comparable<T>。这允许实现对范围的 valuestartendInclusive 进行直接比较。您可以在 contains(value: T).

的实现中看到这一点