6

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.

Pitel
  • 5,334
  • 7
  • 45
  • 72
  • 1
    You could perhaps use `equals()`: https://stackoverflow.com/questions/49349674/case-sensitivity-kotlin-ignorecase – underscore_d Apr 17 '18 at 12:14

2 Answers2

9

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!!)
}
miensol
  • 39,733
  • 7
  • 116
  • 112
-3
var s1 =editText.text.toString()
var s2=textView_.text
var s3 =s1.equals(s2 ,true)
desertnaut
  • 57,590
  • 26
  • 140
  • 166
Ayman Nasr
  • 17
  • 3
  • 3
    While this code may solve the question, [including an explanation](//meta.stackexchange.com/q/114762) of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please [edit] your answer to add explanations and give an indication of what limitations and assumptions apply. – Yunnosch Dec 28 '20 at 21:57
  • Also, since you seem to struggle with it: https://stackoverflow.com/editing-help – Yunnosch Dec 28 '20 at 21:57