Difference between 'contains' and 'containsKey' in Kotlin Map

Viewed 4052
val m = mapOf<String, Int>()
m.contains("Foo")
m.containsKey("Bar")

In Kotlin, there are two methods for Map to check whether the map has specified key: contains and containsKey

I know that key in m is the idiomatic way to check key existence, but I wonder why they have two methods doing same function. Do they have any differences between them? Or are they just some sort of legacy code for compatibility?

2 Answers

They are equivalent. This is the contains method implementation:

@kotlin.internal.InlineOnly
public inline operator fun <@kotlin.internal.OnlyInputTypes K, V> Map<out K, V>.contains(key: K): Boolean = containsKey(key)

According docs:

This method (contains) allows to use the x in map syntax for checking whether an object is contained in the map.

There is no difference between these methods in Map

contains is just generic function, used in different collections with different behaviour (Example: contains object in Collection, but key in Map)

containsKey and containsValue are Maps specific functions

But contains in Map is just a wrapper for containsKey source code:

public inline operator fun <@kotlin.internal.OnlyInputTypes K, V> Map<out K, V>.contains(key: K): Boolean = containsKey(key)
Related