Hi, small question. Is there a way to pattern matc...
# getting-started
l
Hi, small question. Is there a way to pattern match a lambda that receives a Map<K,V>. For example:
Copy code
onSomething { (key,value) : Map<K,V> -> ... }
c
It's not a pattern match, it's just destructuration:
Copy code
mapOf(
    "1" to 1,
    "2" to 2,
).forEach { (key, value) ->
    println("$key → $value")
}
Pattern matching implies some kind of conditional, it's not the case in Kotlin
It also works with regular for loops:
Copy code
val map = mapOf(…)

for ((key, value) in map) {
    …
}
https://kotlinlang.org/docs/destructuring-declarations.html
l
Yes, I thought that should work
Copy code
Destructuring declaration initializer of type Map<String, Boolean>! must have a 'component2()' function
c
Ah, you have the wrong
Map
, you're using
java.util.Map
but you should be using
kotlin.Map
The
!
in the type is a platform type (https://kotlinlang.org/docs/java-to-kotlin-nullability-guide.html#platform-types), it means you're using a type that comes from some other language (in your case, Java) which has missing information
l
I thing the case is that this is a Map<K, out V>
Oh
damn, I cannot change it since it cames from a library 😅
c
You should be able to cast it, the Kotlin Map is an alias for the Java one
by manually casting it you tell the compiler that you yourself have checked for nullability
l
In destructuring-declarations I found the following that worked:
Copy code
aMap.mapValues { (aMapKey, aMapValue) ->
    ...
}
Thanks 😄
j
Yeah you were actually trying to destructure the map itself instead of individual entries, that was your issue
l
Yeah, silly me 😆