For example, filling a crash array with data from another array:
if (datosAccidente.desperfectos.isNotEmpty()) {
rDesperfectos = datosAccidente.desperfectos.map { Desperfecto(it) }
}
or when reading lines from a file:
File("./miFichero.txt").forEachLine { println(it) }
What is it it
and what would it represent in those examples?
Reading the documentation , it is mentioned that it it
is an implicit name for a single parameter, but then why wouldn't it work for a case like the following:
fun test(datos: String) {
var aux: String = it
}
In the documentation you linked it says:
A lambda expression or anonymous function is a "literal function"
And in the definition of
it
explains:Another useful convention is that if a literal function has only one parameter, its declaration can be omitted (along with the ->) and its name will be
it
.Therefore
it
it is a convention to make the declaration of lambda functions even shorter.This does not work with the function declared in the classic way
because the syntax explicitly requires the variable name and its type : The test function can be used in a general way, so the compiler cannot infer the type if it is not defined at this time, whereas lambda functions are declared in the moment in which they are going to be used (they have a very defined context) and, therefore, the type does not have to be defined explicitly.