Salim Mazari Boufares
Salim Mazari Boufares

Reputation: 74

Redundant 'let' call removal alters the semantic

I wrote a code that checks if a number is within a range, the code reads first the number to check then the endpoints values of the range.

The code seems to be fine

fun main() = read().let { print(it  in read()..read()) }
fun read() = readLine()!!.toInt()

If I enter the sequence: 20, 10, 30 I get the expected result (true)

But then the IDE gives me a warning, saying that redundant 'let' call could be removed

enter image description here

And when I click on Remove let call I get the following code:

fun main() = print(read() in read()..read())
fun read() = readLine()!!.toInt()

Which gives me an opposite result (false) using the same sequence 20, 10, 30

I'm quite new in Kotlin, but I'm puzzled because my very first code was the version without the let call, and I've used the scope function to verify it after getting the strange output, I hope someone could explain this.

The IDE details: IntelliJ IDEA 2021.2.1 (Ultimate Edition) Build #IU-212.5080.55, built on August 24, 2021 Runtime version: 11.0.11+9-b1504.16 x86_64 VM: OpenJDK 64-Bit Server VM by JetBrains s.r.o. macOS 10.15.7

Upvotes: 0

Views: 609

Answers (1)

Merig
Merig

Reputation: 2011

The scope block ensures that your first read() runs before the 2 range ones. When you remove it my guess is that the order of operation changes and the values don't go where you expect them.

Try something like

val numberToCheck = read()
val range = read()..read()
print(numberToCheck in range)

Upvotes: 3

Related Questions