hylowaker
hylowaker

Reputation: 1143

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

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?

Upvotes: 8

Views: 10705

Answers (2)

Viktor
Viktor

Reputation: 1147

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)

Upvotes: 9

H&#233;ctor
H&#233;ctor

Reputation: 26034

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.

Upvotes: 7

Related Questions