https://kotlinlang.org logo
#getting-started
Title
# getting-started
r

Ray Rahke

03/03/2024, 7:24 PM
How to get this right? Trying to check if some key,value pair is in a map
a

Adam S

03/03/2024, 7:30 PM
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

ephemient

03/03/2024, 7:31 PM
or just write
Copy code
m["foo"] == 1
like a normal Map usage
1
r

Ray Rahke

03/03/2024, 7:32 PM
@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

ephemient

03/03/2024, 7:32 PM
@Adam S containsKey+containsValue doesn't mean it's in the same mapping…
1
no because that's entries not pairs
r

Ray Rahke

03/03/2024, 7:32 PM
@ephemient your snippet assumes that "foo" is in the map
which will runtime crash right
e

ephemient

03/03/2024, 7:33 PM
it does not
r

Ray Rahke

03/03/2024, 7:33 PM
in kotlin you can do if m["key that has not been added yet"] == whatever
?
e

ephemient

03/03/2024, 7:33 PM
yes of course
r

Ray Rahke

03/03/2024, 7:34 PM
i mean that crashes in js, python i think too
e

ephemient

03/03/2024, 7:34 PM
in what language can you not?
r

Ray Rahke

03/03/2024, 7:34 PM
maybe i am recalling wrong
e

ephemient

03/03/2024, 7:34 PM
ok python
but not JS
a

Adam S

03/03/2024, 7:34 PM
containsKey+containsValue doesn't mean it's in the same mapping…
d'oh, true!
r

Ray Rahke

03/03/2024, 7:34 PM
so it will just return undefined == 1 then?
e

ephemient

03/03/2024, 7:34 PM
null == 1
is false
r

Ray Rahke

03/03/2024, 7:34 PM
yeah
e

ephemient

03/03/2024, 7:35 PM
but you wouldn't write that in Python either
r

Ray Rahke

03/03/2024, 7:35 PM
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

ephemient

03/03/2024, 7:35 PM
just try it
a

Adam S

03/03/2024, 7:36 PM
what about instead of a map, use a list?
Copy code
val m = listOf("foo" to 1, "bar" to 2)