Skip to content

How to use java.String.format in Scala?

In Scala, you can use the format method of the String class to format strings in a way similar to the printf function in C. Here's an example using the idiomatic Scala syntax:

scala
val name = "John"
val age = 30
val formattedString = "Hello, my name is %s and I am %d years old".format(name, age)
println(formattedString)  // Outputs: "Hello, my name is John and I am 30 years old"

You can also use the f string interpolator in Scala to achieve a similar result:

scala
val name = "John"
val age = 30
val formattedString = f"Hello, my name is $name and I am $age%d years old"
println(formattedString)  // Outputs: "Hello, my name is John and I am 30 years old"

The f interpolator allows you to specify format specifiers like %d directly after the $variable, just like with format.

Note that %s and %d are placeholders used by String.format. The f interpolator uses $variable directly for basic substitution. You only need to append a format specifier (like %d, %f, or %s) to a $variable in the f interpolator when you want explicit formatting (e.g., padding, precision, or forcing a specific type representation). You can also use other format specifiers like %f for floating-point numbers and %x for hexadecimal numbers.

Do you find this helpful?

Dual-run preview — compare with live Symfony routes.