Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to run all on an iterable with index in Kotlin

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading