Scala Strings: uppercase, lowercase, and capitalize methods

Scala String FAQ: How do I convert a String to uppercase or lowercase, or capitalize the first character in the string?

Solution

To convert a String to uppercase or lowercase, use the toUpperCase and toLowerCase methods:

scala> "hello".toUpperCase
res0: java.lang.String = HELLO

scala> "Hello".toLowerCase
res1: java.lang.String = hello

To capitalize the first character of a string, use the capitalize method, which appears to be on the String class:

scala> val s = "hello world"
s: java.lang.String = hello world

scala> s.capitalize
res2: String = Hello world

Discussion

With the transparency of the Scala implicit conversion approach, it appears that all three of these methods are in the Java String class, but the reality is that the toUpperCase and toLowerCase methods are on the Java String class, but the capitalize method comes from the Scala StringLike class.

The important thing for you, the developer, is that you can tell which methods are available on a given object. At the time of this writing you can’t see that the capitalize method is available on a String in the REPL, but you can see it in Eclipse. Using Eclipse with the Scala IDE plug-in, create a String like this:

val s = "foo"

Then type s. on the next line of the editor and wait for the code assist dialog to come up (or press Ctrl-Space to display it). The pop-up dialog that appears shows all the implicit methods that are available, including capitalize and many others.

See Also

  • The StringOps class: http://www.scala-lang.org/api/current/scala/collection/immutable/StringOps.html
  • The StringLike trait: http://www.scala-lang.org/api/current/scala/collection/immutable/StringLike.html