Why is this an issue?
it
is a special identifier that allows you to refer to the current parameter being passed to a lambda expression without explicitly
naming the parameter.
How to fix it
Lambda expressions are a concise way of writing anonymous functions. Many lambda expressions have only one parameter, when this is true the
compiler can determine the parameter type by context. Thus when using it
with single parameter lambda expressions, you do not need to
declare the type.
Code examples
Noncompliant code example
This lambda expression uses a single parameter so we do not need to explicitly declare the it
parameter.
listOf(1, 2, 3).forEach { it -> it.and(6) } // Noncompliant
Compliant solution
Instead, we can write this lambda expression without using →
because the compiler assumes that you want to use the implicit
it
parameter to refer to the current element being iterated over.
listOf(1, 2, 3).forEach { it.and(6) } // Compliant
Noncompliant code example
val l1: (Int) -> Int = { it -> it + 5 } // Noncompliant
Compliant solution
In the first example, since since the expression to the left of the arrow is a lambda parameter declaration it, 'it' should be removed. In the
second example, you must use the lambda parameter to be able to declare the parameter type because it can not be inferred from the context.
val l3: (Int) -> Int = { it + 5 } // Compliant
val l3 = {it: Int -> it + 5 } // Compliant, need to know the type
Resources
Documentation
Articles & blog posts