This article explores different ways to determine if an element is present in a Kotlin Set.

1. Using contains() function

In Kotlin, the recommended way to check if an element is present in a Set is using the contains() function. It returns a boolean value true if the set contains the specified element, false otherwise.

Download Code

 
The default implementation of the equals() and hashCode() functions only checks for the reference equality. For instance, the following code returns false.

Download Code

 
Therefore, don’t forget to override equals and hashCode functions while constructing the Set of custom objects. Both these functions can be auto-generated with IntelliJ IDEA.

Download Code

2. Using any() function

Alternately, you can use the any() function that returns true if at least one element matches with the given predicate. The following code example shows invocation for this function:

Download Code

That’s all about determining if an element is present in a Kotlin Set.