Applying suggestion changes the intended behaviour of code


#1

I’m trying to apply a code optimisation suggestions provided by IntelliJ IDEA CE.
Below is a code sample:

(0 until 10).forEach {
    val target = it
    (10 until 20).forEach {
        println(it + target)
    }
}

Here IJ provides suggestion for variable target on line 2 as “Variable is an exact copy of another variable and can be inlined” and after applying the suggestion code becomes:

(0 until 10).forEach {
    (10 until 20).forEach {
        println(it + it)
    }
}

Wouldn’t it be better for nested sequences to have local parameters being passed to lambdas instead of relying on default parameter it ?


#2

Should be a bug, but anyway, instead of val target = it, why not using an explicit argument name?

(0 until 10).forEach { target ->
    (10 until 20).forEach {
        println(it + target)
    }
}

#3

I agree, in this scenario, it is better to use an explicit argument beforehand instead of using the IDE suggestion and spending a couple of hour debugging the unexpected glitch. :disappointed_relieved: