Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Case insensitive when

Tags:

kotlin

Is it somehow possible to make when String comparison case insensitive by default?

when (subtype.toLowerCase()) {
    MessagingClient.RTC_SUBTYPE.sdp.toString().toLowerCase() -> onSDPMessageReceived(topic, sender, data!!)
    MessagingClient.RTC_SUBTYPE.bye.toString().toLowerCase() -> onRTCBYEMessageReceived(topic, sender)
    MessagingClient.RTC_SUBTYPE.negotiationOffer.toString().toLowerCase() -> onNegotiationOfferMessageReceived(sender, data!!)
}

This has too much repetetive code! Also note that MessagingClient.RTC_SUBTYPE is enum class and subtype on the first line is received from some client, so we must treat it accordingly.

like image 624
Pitel Avatar asked Apr 17 '18 12:04

Pitel


People also ask

What does case-insensitive mean?

case insensitive (not comparable) (computer science) Treating or interpreting upper- and lowercase letters as being the same.

What is the problem with case-sensitive names?

What do case sensitive computer programs do? Case sensitive programs recognize and distinguish case in file names and queries, but sometimes they will not return the correct file or perform the intended function without the correct case.

What is usually case-sensitive?

Text or typed input that is sensitive to capitalization of letters. For example, "Computer" and "computer" are two different words because the "C" is uppercase in the first example and lowercase in the second example. On modern systems, passwords are case-sensitive, and usernames are usually case-sensitive as well.

What is case-insensitive matching?

Case insensitive matching is most frequently used in combination with the Windows file systems, which can store filenames using upper and lowercase letters, but do not distinguish between upper and lowercase characters when matching filenames on disk.


1 Answers

I would convert subtype to MessagingClient.RTC_SUBTYPE like so:

val subtypeEnum = MessagingClient.RTC_SUBTYPE.values().firstOrNull {
   it.name.equals(subtype, ignoreCase = true) 
} ?: throw IllegalArgumentException("${subtype} no value of MessagingClient.RTC_SUBTYPE match")

And then use it in when

when (subtypeEnm) {
    MessagingClient.RTC_SUBTYPE.sdp -> onSDPMessageReceived(topic, sender, data!!)
    MessagingClient.RTC_SUBTYPE.bye -> onRTCBYEMessageReceived(topic, sender)
    MessagingClient.RTC_SUBTYPE.negotiationOffer -> onNegotiationOfferMessageReceived(sender, data!!)
}
like image 97
miensol Avatar answered Sep 30 '22 06:09

miensol