1. Introduction

Enums are a powerful feature in Kotlin that allows programmers to define a set of named constants. They’re often used to represent a closed set of values, such as the days of the week or the months of the year. Sometimes, we may need to check if a certain string value is contained in an enum.

In this tutorial, we’ll explore various ways to check if an enum value contains a given string in Kotlin.

2. Enum Class Definition

Throughout this tutorial, we’re going to look at various approaches and techniques to check if an enum value contains a certain string. First, let’s first define our Enum constants:

enum class DaysOfWeek {
    MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY

    companion object {
        val names by lazy { DaysOfWeek.values().map{ it.name } }
    }
}

Our enum class contains seven values, representing the days of the week. In addition, this class contains a companion object that generates the names for each enum constant using the map() method. This creates a list of string values from the names that we’ll be able to use later.

3. Using a for() Loop

We can check if an enum value contains a specific string by using a classic for() loop:

fun containsValueUsingForLoop(value: String): Boolean {
    for (day in DaysOfWeek.values()) {
        if (day.name == value) {
            return true
        }
    }
    return false
}

In this method, we iterate over all the enum constants and check if the given string matches any enum’s name.

It’s always a good idea to unit-test our code to ensure it works as we expect:

@Test
fun `checks if enum value contains a specific string correctly using for loop`() {
    assertFalse(containsValueUsingForLoop("RED"))
    assertTrue(containsValueUsingForLoop("WEDNESDAY"))
    assertFalse(containsValueUsingForLoop("AUGUST"))
    assertTrue(containsValueUsingForLoop("SATURDAY"))
}

In this code, we use our helper method to ascertain if any enum value contains a given string. Using assert statements, we assert that our enum does not contain the strings “RED” and “AUGUST”. However, our enum contains the strings “WEDNESDAY” and “SATURDAY” as expected.

4. Using the when() Expression

We can equally use a when() expression to check if a given string is contained within an enum value:

fun containsValueUsingWhenExpression(value: String): Boolean {
    return when (value) {
        in DaysOfWeek.names -> true
        else -> false
    }
}

Unlike the helper method from the previous technique, this method does not perform iteration but simply uses a when() expression to check if the given value matches the name of any of the names of the enum constants. It returns true if there is a match, and false otherwise. Notice that this is using our helper property of the list of names from the enum.

Let’s test our helper method as well:

@Test
fun `checks if enum value contains a specific string correctly using when expression`() {
    assertFalse(containsValueUsingWhenExpression("RED"))
    assertTrue(containsValueUsingWhenExpression("WEDNESDAY"))
    assertFalse(containsValueUsingWhenExpression("AUGUST"))
    assertTrue(containsValueUsingWhenExpression("SATURDAY"))
}

Our helper method correctly reports whether a given string matches the name of any of the enum constants.

5. Using the map() Method

As referenced earlier, we can leverage the map() method as well. We can use the map() method to generate a list containing all the names of our enum constants, and then see if a given string is contained in the list of names:

@Test
fun `checks if enum value contains a specific string correctly using map method`() {
    val names = DaysOfWeek.values().map { it.name }

    assertFalse(names.contains("RED"))
    assertTrue(names.contains("WEDNESDAY"))
    assertFalse(names.contains("AUGUST"))
    assertTrue(names.contains("SATURDAY"))
}

The map() method returns a list of the names of all the constants in the enum class. Subsequently, we use the contains() method on the list of names to check if a given string is present in it. If it’s present, then the result of this expression will be true; otherwise, it will be false.

5.1. Using the any() Method

However, the map() method approach must apply the lambda function on all the enum constants unavoidably. So, as an optimization strategy, we can use any() instead.

The any() method accepts a lambda function and returns true once the condition in the lambda function holds for any array entry:

@Test
fun `checks if enum value contains a specific string correctly using any method`() {
    val names = DaysOfWeek.values()
    assertFalse(names.any{ it.name == "RED" })
    assertTrue(names.any{ it.name == "WEDNESDAY" })
    assertFalse(names.any{ it.name == "AUGUST" })
    assertTrue(names.any{ it.name == "SATURDAY" })
}

We use the values() method to obtain an array of all the enum constants, and the any() method checks if any of the enum constants in that array have a name equal to the given value.

This approach is better than the map() method approach because it stops looking once it finds a match. Notice that we don’t transform the values() first, and instead only unwrap the name inside the any() check.

6. Using a HashSet

Lastly, we can also check if an enum value contains a given string by creating a HashSet that contains the names of all enum constants:

fun containsValueUsingHashSet(value: String): Boolean {
    val set = HashSet<String>()
    DaysOfWeek.values().forEach { set.add(it.name) }
    return set.contains(value)
}

This helper method will create a HashSet of the names of DaysOfWeek. We can then check if the set contains the given value using the contains() method.

As always, we need to test this as well:

@Test
fun `checks if enum value contains a specific string correctly using a hashset`() {
    assertFalse(containsValueUsingHashSet("RED"))
    assertTrue(containsValueUsingHashSet("WEDNESDAY"))
    assertFalse(containsValueUsingHashSet("AUGUST"))
    assertTrue(containsValueUsingHashSet("SATURDAY"))
}

In this test, we can easily assert the strings “WEDNESDAY” and “SATURDAY” match a name in our enum constants.

7. Conclusion

In this article, we’ve explored various ways to check if an enum value contains a given string in Kotlin. By having multiple ways to achieve the same result, we have the flexibility to choose the one that suits our needs best. Moreover, having different options available can help us avoid potential pitfalls and limitations that may arise when using a particular method.

Furthermore, the range of options available enables us to learn different Kotlin language constructs and concepts that can help us become better programmers. Therefore, it’s important to be aware of the different ways to check if an enum contains a string so that we can make informed decisions when writing code.

As always, the code samples and test cases relevant to this article can be found over on GitHub.
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.