Hi guys, I am getting difficult to understand this...
# codereview
k
Hi guys, I am getting difficult to understand this piece of code. I don't understand how
let
is going inside the lambda block if value is null. Can someone guide me on this. Thanks
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. Example 1:
Copy code
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
Example 2:
Copy code
Input: nums = [3,2,4], target = 6
Output: [1,2]
Example 3:
Copy code
Input: nums = [3,3], target = 6
Output: [0,1]
I am adding piece of code.
Copy code
fun main() {
//    val nums = intArrayOf(2, 7, 11, 15)
//    val target = 9
    val nums = intArrayOf(3, 2, 4)
    val target = 6
//    val nums = intArrayOf(3, 3)
//    val target = 6
    twoSum(nums, target).forEach {
        print(" $it")
    }
}

fun twoSum(nums: IntArray, target: Int): IntArray {
    val map = mutableMapOf<Int, Int>()
    nums.forEachIndexed { index, i ->
        map[i]?.let {
            return intArrayOf(it, index)
        }
        map[target - i] = index
    }
    return intArrayOf()
}
My

youtube

link is described that I am debugging the code. My question is how
Copy code
map[i]?.let {
                return intArrayOf(it, index)
            }
is going inside the 1st and 2nd iteration of
return
statment and it not going in 3rd iteration. Can anyone help me on this. Thanks
t
Hi, i didn’t check your entire sample, but it sounds like you missing the understanding for the safe call operator (?.) https://kotlinlang.org/docs/null-safety.html#safe-calls there is also an example on that page using let to println only values that are not null, which should be similar to your case. -> it?.let is therefor often used as a if(it != null) replacement
k
Hi @Thomas Urbanitsch my let statment is null so how it going inside me lambda function.
My question is that if
map[i]?
is null in 1st iteration then how should it be going inside the lambda and call
intArrayOf(it, index)
?
Thanks for your time.
t
https://pl.kotl.in/Hu2kAP1Ck it is only entering the let in case map[i] != null (as expected)
k
yes in your code it working fine. But In my intellj it going inside the blog. You can clearly see in the video link

https://www.youtube.com/watch?v=tCG4i0q3Zf4&amp;feature=youtu.be

t
i just don’t think intellij is showing you the correct lines highlighted there while debugging, otherwise you would also expect your return statement leaving your method, right? :)
k
yes intellj is not showing me correct lines highlighting there while debugging. Yes answer is return the statement