Home > Software design >  How to run all on an iterable with index in Kotlin
How to run all on an iterable with index in Kotlin

Time:04-15

In Kotlin is there function or a way to also have an index when using the all extension?

With this kind of situation:

val givenKeys = arrayOf("SHIFT", "BUILDING", "FLOOR")
val givenVals = arrayOf("NIGHT", "ALPHA", "THIRD")
val successfulMatch = mapOf(
    Pair("SHIFT", "NIGHT"), Pair("BUILDING", "ALPHA"), Pair("FLOOR", "THIRD")
)
val unsuccessfulMatch = mapOf(
    Pair("SHIFT", "NIGHT"), Pair("BUILDING", "BETA"), Pair("FLOOR", "FIRST")
)

fun isMatch(candidate: Map<String, String>, keys: Array<String>, vals: Array<String>): Boolean {
    var matches = true
    keys.forEachIndexed { i, key ->
        if(!candidate.containsKey(key) || vals[i] != candidate[key]) {
            matches = false
        }
    }
    return matches
}

isMatch(successfulMatch, givenKeys, givenVals) // returns true
isMatch(unsuccessfulMatch, givenKeys, givenVals) // returns false

I want to do something like this

fun isMatch(candidate: Map<String, String>, keys: Array<String>, vals: Array<String>): Boolean {
    return keys.allIndex {i, key ->
        candidate.containsKey(key) && vals.any {it == candidate[key]}
    }
}

Is there any function like that?

CodePudding user response:

You can use withIndex:

return keys.withIndex().all { (i, key) ->
    //...
}

Note that it creates an Iterable<IndexedValue>, so you would typically use the dereference operator ( ) for the lambda parameter.

  • Related