1
var t = 0
fun sumIntMap(hm: HashMap<Int,Int>) = hm.forEach{ x -> t+=x.value 
}.let { t }

Trying to sum a Hashmap Int values here with a function, I cannot seem to optimize it so that it requires not capturing and needing the temp var (t).

How can I use temp vars in lambdas and return them? Is how I wrote it the only real way (using a let to return the temp var)?

Thanks!

1 Answer 1

4

You can map your HashMap entries to their values to get a List of Ints, and then sum the values in that list:

hm.map { it.value }.sum()

If you have a List instead of a Map, you can also use fold or reduce to do similar things to your original code:

hm.toList().fold(0, { acc, pair -> acc + pair.second })
Sign up to request clarification or add additional context in comments.

5 Comments

Hi there, really I was looking at the general concept of returning a specific value from a lambda when the lambda handles multiple vars (in this case x & t) using let allows me to do this but can it be done within the lambda itself without chaining?
@HiLo, I'm not 100% sure what you're asking, but maybe you're looking for reduce, which is really a more general sum.
You'll either have to chain calls or use an operator like fold or reduce - those are only available on a List though, not a Map. I've edited my answer with a solution using fold which looks more like your code, that operator might be what you're looking for.
I believe you could even destructure pair into (_, value), perhaps this fits with Kotlin's functional features :)
@HiLo the concept you are talking about is fold. Read the second part of @zsmb13 's answer, he's right. The 0 replaces your t = 0 and acc is effectively your t. Also note that you can just do 'hm.values' to get the values: hm.values.fold(0) { t, v -> t + v}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.