Scala: How to convert multiple spaces to a single space (regex)

Here’s a quick Scala example that shows how to convert multiple spaces in a string to a single space:

scala> val before = "  foo  bar   baz bonk "
before: String = "  foo  bar   baz bonk "

scala> val after = before.trim.replaceAll(" +", " ")
after: String = foo bar baz bonk

As that example shows, the key is to first call trim to remove any leading and trailing spaces, and then call replaceAll to convert one or more blank spaces to a single space:

val after = before.trim.replaceAll(" +", " ")

(The code I show is a simple adaptation of the Java code I found on SO.)

“Treat every moment as your last.
It is not preparation for something else.”
~ Shunryu Suzuki