I have one let
inside another one
someMethodCall()?.let{
// ....
// some code here
// ....
val resultCall = it
someMethod2Call()?.let {
// ...
val myVariable = it + resultCall
// ...
}
}
Is it possible in Kotlin inside the second let
get access to it
of first let
and avoid using resultCall
variable?
Higher-Order Function – In Kotlin, a function which can accept a function as parameter or can return a function is called Higher-Order function. Instead of Integer, String or Array as a parameter to function, we will pass anonymous function or lambdas.
The lateinit keyword allows you to avoid initializing a property when an object is constructed. If your property is referenced before being initialized, Kotlin throws an UninitializedPropertyAccessException , so be sure to initialize your property as soon as possible.
flatMap() When mapping an Optional in Java, sometimes you have to unwrap another Optional . To do this, you use flatMap() instead of map() . With Kotlin's null system, the value is either present, or null , so there's nothing to unwrap.
No it's not possible and you should definitely use explicit names for the parameters in such use cases:
someMethodCall()?.let{ v1->
// ....
// some code here
// ....
someMethod2Call()?.let { v2->
}
}
it
is a default name for the lambda argument. it
is convenient for short lambdas, but you should not use it for longer lambdas. For longer lambdas make the code more readable by specifying an explicit argument name:
someMethodCall()?.let {
resultCall ->
// ... some code that uses "resultCall" instead of "it" ...
}
Use different names to avoid shadowing of the variable in the inner block as in your example:
someMethodCall()?.let {
resultCall ->
// ... some code here ...
someMethod2Call()?.let {
resultCall2 ->
// ...
val myVariable = resultCall2 + resultCall
// ...
}
It helps if you name your variables.
someMethodCall()?.let { resultCall ->
// ....
// some code here
// ....
someMethod2Call()?.let { otherResult ->
// ...
val myVariable = resultCall + otherResult
// ...
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With