Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

`let` inside `let` in Kotlin: how to access the first `it`

Tags:

kotlin

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?

like image 666
Vitalii Avatar asked Jun 10 '18 19:06

Vitalii


People also ask

What is high order function in Kotlin?

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.

What is Lateinit in Kotlin?

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.

How do you unwrap optional in Kotlin?

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.


3 Answers

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->

    }
}
like image 28
s1m0nw1 Avatar answered Dec 01 '22 00:12

s1m0nw1


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
        // ... 
    }
like image 150
battlmonstr Avatar answered Dec 01 '22 00:12

battlmonstr


It helps if you name your variables.

someMethodCall()?.let { resultCall ->
    // ....
    // some code here
    // ....
    someMethod2Call()?.let { otherResult ->
        // ...
        val myVariable = resultCall + otherResult
        // ... 
    }
}
like image 24
EpicPandaForce Avatar answered Nov 30 '22 23:11

EpicPandaForce