toLowerCase() lint warnings

You may run across a lint warning in Java or Kotlin on when using String.toLowerCase().

"Implicitly using the default locale is a common source of bugs: Use toLowerCase(Locale) instead."

So we can slap a @SupressWarning on the method and be done, right?

NOPE

What is not immediately obvious is that the lowercase behavior can change depending on the locale, and these call Locale.getDefault() under the covers. In some locales, this can break your code!

Imagine you need to construct a url given someone’s name. The server expects all paths to be in lowercase, so you do something like this:

val imageUrl = "https://myserver.com/${name.toLowerCase()/profile.jpg"
imageView.load(imageUrl)

Doing name.toLowerCase() in some locales can cause the letters to change. Case in point is Turkey. In this locale a capital ‘I’ will become a lowercase dotless ‘i’.

Lesson here is: if you need to lowercase internal strings, such as URLs or identifiers, use Locale.ROOT.

val imageUrl = "https://myserver.com/${name.toLowerCase(Locale.ROOT)/profile.jpg"<br> imageView.load(imageUrl)

Note: Kotlin also has String.toUpperCase(), which will case a lint warning as well. In Kotlin 1.3.50 there is a String.toUpperCase(Locale) marked as experimental. This is an option, but you may have to suppress the new lint warning.

Software Engineer, Husband, and father of 2 amazing kids. Android, iOS, Kotlin multiplatform!! Maintainer of ReduxKotlin.org