O'Reilly logo

Scala Puzzlers by Nermin Šerifovic, Andrew Phillips

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Puzzler 21

I Can Has Padding?

Scala provides an incremental string builder that shares the same name as, and therefore hides, java.lang.StringBuilder. Scala's StringBuilder is similar to Java's for the most part, differing mainly where providing the same methods as the Java class would conflict with the Scala collections library. And like java.lang.StringBuilder, Scala's StringBuilder is not synchronized, leaving you to handle thread safety by other means.

The following program demonstrates a StringBuilder in action. What does it do?

  implicit class Padder(val sb: StringBuilderextends AnyVal {
    def pad2(width: Int) = {
      1 to width - sb.length foreach { sb += '*' }
      sb
     }
  }
    // length == 14
  val greeting = new StringBuilder("Hello, kitteh!" ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required