Search code examples
kotlinin-operator

Using in operator to compare string with range of strings


I am using in operator to check whether a value is in range. But I am not able to understand exactly how the comparison with range of strings is done. Below are the few arguments and their output which I have tried:

   println("KOTLIN" in "J".."K")
false

   println("KOTLIN" in "Java".."Scala")
true

    println("KOTLIN" in "Java".."Bhuv")
false

Solution

  • in is compiled down to the following function (defined in kotlin.ranges.Range.kt):

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

    So "KOTLIN" in "J".."K" results in:

    ("J".."K").contains("KOTLIN")
    

    The comparison in this case relies on normal String comparisons since >= and <= are compiled down to variations of compareTo. The implementation looks as follows:

    public int compareTo(String anotherString) {
        int len1 = value.length;
        int len2 = anotherString.value.length;
        int lim = Math.min(len1, len2);
        char v1[] = value;
        char v2[] = anotherString.value;
    
        int k = 0;
        while (k < lim) {
            char c1 = v1[k];
            char c2 = v2[k];
            if (c1 != c2) {
                return c1 - c2;
            }
            k++;
        }
        return len1 - len2;
    }
    

    So, "KOTLIN" in "Java".."Scala" is equal to the following:

    "KOTLIN".compareTo("Java") >=0 && "KOTLIN".compareTo("Scala") <= 0