Kotlin check List contain ignore case

569 views Asked by At

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

2

There are 2 answers

0
hazra On

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 }
0
aneroid On

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.