Use it in lambda expression


I wrote following lambda expression

val positive:(Int)-> Boolean={x:Int -> x >0}

It works
val positive:(Int)-> Boolean={it >0}
it works too

but why this gives error ERROR Unresolved reference: it
val positive={it >0}

In the third case you never told the compiler that you have a lambda with a single argument.

It won’t “guess” that for you.

The example in your link is different you’re calling a method which requires a single-argument lambda hence the compiler knows that there’s a single argument.

Note that way you use lambda is a bit atypical, usually lambdas are used a “quick” inline functions you use in some statement. If you want to define a function, you’d usually use fun


For this case a type can’t be infered. What you can use is this instead:

val positive = { it: Int -> it > 0 }
1 Like