Consider a Scala string
that has values in it. For example, with "10 cats" we have the value 10, and some following text. With format we can generate this text.
With Java we have standard string
format insertion points like "%d" for an Int
. In Scala 3.3 we keep the same format codes.
Let us begin with a simple example. We have a number 10 (specified with the val
keyword). We call format()
with this Int
.
formatted()
method can be called on any object—so we can use it on an Int
, Double
or String
value.string
to the formatted method. This uses the same format as String.format
in Java.object Program { def main(args: Array[String]): Unit = { val number = 10 // Use a format string. val result = "There are %d cats.".format(number) println(result) } }There are 10 cats.
This is called on a format string
. We pass it arguments that are placed in the format insertion codes. Here we insert an Int
and a floating-point (Double
) with "%d" and "%f."
object Program { def main(args: Array[String]): Unit = { // An example format string. val f = "I have %d dogs that weigh on average %f pounds." // An Int and Double for the format string. val count = 4 val averageWeight = 14.5 // Call format on the format string and print the result. val result = f.format(count, averageWeight) println(result) } }I have 4 dogs that weigh on average 14.500000 pounds.
Here we apply right and left padding to Ints and strings to justify text. For padding, we use the "-10s" and "10s" format codes for right and left padding insertions.
String.format
method.object Program { def main(args: Array[String]): Unit = { val lefts = List(10, 200, 3000) val rights = List("cat", "fish", "elephant") // Loop over indexes. for (i <- 0.until(lefts.length)) { // Get element from each list at this index. val left = lefts(i) val right = rights(i) // Use this format string. val padding = "%1$-10s %2$10s" // Call format to apply padding. val result = padding.format(left, right) println(result) } } }10 cat 200 fish 3000 elephant
We can use a format string
and the format()
method to reorder and repeat values in a string
. Consider this example. We have 3 insertions.
object Program { def main(args: Array[String]): Unit = { // Specify the second argument is placed first. // ... We can reorder and repeat arguments. val result = "%2$s %1$s %2$s".format("frog", "cat") println(result) } }cat frog cat
Formatting strings in Scala is done in a standard way (with the same literal syntax as Java). But with format()
we can format values in a clearer way—with just a method call.