How to get this right? Trying to check if some key...
# getting-started
r
How to get this right? Trying to check if some key,value pair is in a map
a
in
is the representation for the
contains(...)
operator function https://kotlinlang.org/docs/operator-overloading.html#in-operator So in IntelliJ you can always use
m.contains(...)
to see the auto complete suggestions, and there's none for checking if a Pair exists in a map. You can write your own one though:
Copy code
@Deprecated("Bugged! See thread below")
operator fun <K, V> Map<K, V>.contains(keyValue: Pair<K, V>): Boolean =
  containsKey(keyValue.first) && containsValue(keyValue.second)
e
or just write
Copy code
m["foo"] == 1
like a normal Map usage
1
r
@Adam S is there one for m.entries.contains()?
i am surprised if there is not anything built in for such a reasonable operation
e
@Adam S containsKey+containsValue doesn't mean it's in the same mapping…
1
no because that's entries not pairs
r
@ephemient your snippet assumes that "foo" is in the map
which will runtime crash right
e
it does not
r
in kotlin you can do if m["key that has not been added yet"] == whatever
?
e
yes of course
r
i mean that crashes in js, python i think too
e
in what language can you not?
r
maybe i am recalling wrong
e
ok python
but not JS
a
containsKey+containsValue doesn't mean it's in the same mapping…
d'oh, true!
r
so it will just return undefined == 1 then?
e
null == 1
is false
r
yeah
e
but you wouldn't write that in Python either
r
for my use case I dont really want to use a map. I rather just want a set of pairs.
that should be easy with
in
keyword yeah?
if Pair("foo", 1) in setofpairs
e
just try it
a
what about instead of a map, use a list?
Copy code
val m = listOf("foo" to 1, "bar" to 2)