'Kotlin check List contain ignore case

Having the equals ignore case option

 if (bookType.equals(Type.BABY.name, true))

Is there an option to do contain similar with ignore case?

 val validTypes = listOf("Kids", "Baby")

 if (validTypes.contains(bookType)))

I see there is an option of doing :

  if (bookType.equals(Type.BABY.name, true) || bookType.equals(Type.KIDS.name, true))

But I want more elegant way



Solution 1:[1]

Could use the is operator with a when expression, and directly with book rather than bookType:

val safetyLevel = when (book) {
    is Type.BABY, is Type.KIDS -> "babies and kids"
    is Type.CHILD -> "okay for children"
    else -> "danger!"
}

See Type checks and casts.

Solution 2:[2]

Perhaps you could make the valid types list all uppercase then you can do the following:

You could use map to convert the case for all items in the list e.g.

validTypes.contains(bookType.uppercase())

Or you could use any (https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/any.html)

validTypes.any { bookType.uppercase() == it }

If you want to keep the casing of your original list you could do:

validTypes.any { bookType.replaceFirstChar { it.uppercaseChar() } == it }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 aneroid
Solution 2