Why compiler warning me to avoid `a > 0 &&a...
# compiler
t
Why compiler warning me to avoid
a > 0 && a < 10
and replace with range as
a in 1..9
? Why "primitive" comparisons are not recommended in favor of Ranges instances to call a contains operator? Is there any article/resources explaining the recomendation?
d
a in 1..9
is much more readable than
a > 0 && a < 10
And
in
operator in this case actually optimized by compiler
Copy code
fun test_1(x: Int) {
    if (x in 10..20) {
        println()
    }
}

/*
L0
 LINENUMBER 2 L0
 BIPUSH 20
 BIPUSH 10
 ILOAD 0
 ISTORE 1
 ILOAD 1
 IF_ICMPLE L1
 POP
 GOTO L2
L1
 ILOAD 1
 IF_ICMPLT L2
L3
 LINENUMBER 3 L3
L4
 GETSTATIC java/lang/System.out : Ljava/io/PrintStream;
 INVOKEVIRTUAL java/io/PrintStream.println ()V
L5
L2
 LINENUMBER 5 L2
 RETURN
 */

// ------------------------------------------------------------------------------

fun test_2(x: Int) {
    if (x >= 10 && x < 20) {
        println()
    }
}

/*
L0
 LINENUMBER 33 L0
 ILOAD 0
 BIPUSH 10
 IF_ICMPLT L1
 ILOAD 0
 BIPUSH 20
 IF_ICMPGE L1
L2
 LINENUMBER 34 L2
L3
 GETSTATIC java/lang/System.out : Ljava/io/PrintStream;
 INVOKEVIRTUAL java/io/PrintStream.println ()V
L4
L1
 LINENUMBER 36 L1
 RETURN
 */
🙏 1
👍 1
2
f
What @dmitriy.novozhilov wrote. You might ask why Kotlin cares about style but it's more than style and readability. By using the recommended syntax you also opt-in for any possible future optimizations on a bytecode level that Kotlin might implement, whereas
0 < x && x < 10
cannot be further optimized, as it's not providing the compiler the knowledge regarding what's happening on each side of the branch.
1
j
does FIR tokenize to
in ..
?
d
What do you mean?
j
does it identify range comparisons like this question presents and promote the IR to be "in" ?
we are told that FIR performs lossy output, like promoting
if
to
when
, and so on.
d
This optimization is performed in backend, so there is no difference which frontend is used
j
your answer brought to mind that we have FIR acting on some reduced dimension representation of our code presumably in favor of such things as IR/bytecode level optimizations. the degree to which the FIR is changing the input to IR isn't specified in much detail so I thought I would ask
n
As a side note, using the recommended range can produce pretty unreadable code. For example,
maxDuration > 0L && currDuration >= maxDuration
is suggested to be transformed into
maxDuration in 1..currDuration
, which is terrible (maxDuration is a constant, 0 means don't check).