52 lines
1.9 KiB
Plaintext

== 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.
[source,kotlin]
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.
[source,kotlin]
listOf(1, 2, 3).forEach { it.and(6) } // Compliant
==== Noncompliant code example
[source,kotlin]
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.
[source,kotlin]
val l3: (Int) -> Int = { it + 5 } // Compliant
val l3 = {it: Int -> it + 5 } // Compliant, need to know the type
== Resources
=== Documentation
* https://kotlinlang.org/docs/lambdas.html#lambda-expression-syntax[Kotlin Documentation - Lambdas]
* https://kotlinlang.org/docs/lambdas.html#it-implicit-name-of-a-single-parameter[Kotlin Documentation - "it" parameter]
=== Articles & blog posts
* https://blog.logrocket.com/a-complete-guide-to-kotlin-lambda-expressions/[A complete guide to Kotlin lambda expressions]