Explain Codes LogoExplain Codes Logo

How to use java.String.format in Scala?

java
string-formatting
scala
advanced-formatting
Alex KataevbyAlex Kataev·Aug 8, 2024
TLDR

You can use Java's string formatting in Scala thanks to the language's seamless interoperability. Here’s how:

val formatted = "%s has achieved %d victories!".format("Alice", 42)

Output: "Alice has achieved 42 victories!".

Brace yourself for efficient string formatting and enchanting code comments in Scala.

Practical string formatting for beginners

String formatting in Scala is effortless with the format method which is adapted from Java's String.format. Here's how:

val name = "Alice" val greeting = "Hello, %s!".format(name) // Outputs: "Hello, Alice!"

When referring to indexed arguments, use the $s notation like %1$s. This allows Scala to faithfully adhere to the syntax of Java’s Formatter class.

val result = "%1$s has %2$d apples and %3$d oranges".format("Alice", 3, 5) // Outputs: "Alice has 3 apples and 5 oranges" // Hang on! How did Alice gather so many fruits? 🤔

How to handle common issues in string formatting

Incorrect specifiers or placeholders in the format string can lead to java.util.UnknownFormatConversionException, but fear not for we have a solution:

Ensure you avoid using simple numbered specifiers (%1, %2) which can cause this exception, and stick to the safer %1$s, %2$s notation:

val robust = "%1$s passed the %2$s exam".format("Alice", "Scala") // Output: "Alice passed the Scala exam" // Interesting. Alice seems to be a Scala nerd 🤓💻

Mastering type-specific formatting

Go beyond the basics and get your hands dirty with type-specific formatting.

For floating-point numbers, use %.2f to limit two decimal places:

val pi = "Pi value is %.2f".format(math.Pi) // Output: "Pi value is 3.14" // And you thought Pi was just a Raspberry 💻🍰

For long integers, use %,d to ease readability with comma separation:

val population = "Global population: %,d".format(7800000000L) // Output: "Global population: 7,800,000,000" // That's a lot of people! How many of them do you think are coders? 💭🌎

Exploit advanced formatting for pro-level code

Now let's raise the bar a notch and try some advanced formatting.

For repeating arguments in your format, references make it a breeze:

val echo = "%1$s... %1$s... %1$s...".format("Echo") // Output: "Echo... Echo... Echo..." // Perfect for lost heroes in a cave 😄

Also, you can combine conditional logic with format for dynamic string construction:

val score = 98 val message = "You %s the test".format(if (score > 50) "passed" else "failed") // Output: "You passed the test" // I knew you could do it! 🎉

And for multilines, triple quotes ease the task:

val letter = """Dear %s, | |We are delighted to inform you that your submission "%s" has been accepted! |""".stripMargin.format("Alice", "A Journey With Scala") // Now that's a headline, Alice is on fire! 🚀🎉