Lambda not working as expeccted


#1
package moreorless.ian


fun unaryOperation(x:Int, op:(Int) -> Int){


}
fun outsideFunction() {
    for (number in 1..30){
        unaryOperation(20, { x-> println(number)

            x * number

        })
    }

}

fun main(args: Array<String>) {

    outsideFunction()


}

does not print 1
2
3
etc

only if i add println(x) after the for loop outside lambda ? why?


#2

You pass the lambda as op parameter to unaryFunction, but you do not invoke that op function. So the code in the lambda is not executed.


#3

Following on what @ilya.gorbunov said, if you change your unaryFunction to this:

fun unaryOperation(x:Int, op:(Int) -> Int) = op(x)

then it should work as you expected.


#4

This changed in kotlin 1.2 as in 1.1 no issues happened. Am i incorrect in this understanding @ilya.gorbunov?

thanks again!!


#5

Nothing has been changed in this regard. This code works the same way in any Kotlin version from 1.0 to the current one.