3

I am trying to convert an Array via fold into an indexed Map. Somehow IntelliJ flags that when I return the accumulator that it expects Unit. When I remove the return it complains that I require the datatype I originally wanted to return.

The code is as follows (Item is just a data class)

    constructor(vararg items: Item){
    val itemMap = items.fold(mutableMapOf<Int, MutableList<Item>>(), { acc, item ->
        if (acc.containsKey(item.state)) {
            acc[item.state]?.add(item)
        } else {
            acc.put(item.state, mutableListOf(item))
        }
        return acc
    })

}

Its a bit late here so I probably miss something very obvious. Any help would be very appreciated.

Thanks

3
  • 1
    Remove the return. Commented Dec 26, 2017 at 14:30
  • 6
    FWIW, you can also achieve this entire thing with val itemMap = items.groupBy { it.state }. Commented Dec 26, 2017 at 14:32
  • Thanks @OliverCharlesworth. This is a lot easier. I didn't know about the groupBy function. Commented Dec 26, 2017 at 15:56

1 Answer 1

13

Use the qualified return@fold operator instead of return. In Kotlin, return without a qualifier means 'return from the innermost fun (ignoring lambdas)'.

val itemMap = items.fold(mutableMapOf<Int, MutableList<Item>>(), { acc, item ->
    if (acc.containsKey(item.state)) {
        acc[item.state]?.add(item)
    } else {
        acc.put(item.state, mutableListOf(item))
    }
    return@fold acc
})

See Whats does “return@” mean?, Return at Labels in the language reference.

Or just use the result expression, omitting return:

val itemMap = items.fold(mutableMapOf<Int, MutableList<Item>>(), { acc, item ->
    if (acc.containsKey(item.state)) {
        acc[item.state]?.add(item)
    } else {
        acc.put(item.state, mutableListOf(item))
    }
    acc
})

Basically, this kind of fold is implemented in the standard library: see .groupBy { ... }.

Sign up to request clarification or add additional context in comments.

Comments

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.