With too many arguments, String.format
easily gets too confusing. Is there a more powerful way to format a String. Like so:
"This is #{number} string".format("number" -> 1)
Or is this not possible because of type issues (format
would need to take a Map[String, Any], I assume; don’t know if this would make things worse).
Or is the better way doing it like this:
val number = 1
<plain>This is { number } string</plain> text
even though it pollutes the name space?
Edit:
While a simple pimping might do in many cases, I’m also looking for something going in the same direction as Python’s format()
(See: http://docs.python.org/release/3.1.2/library/string.html#formatstrings)
You can easily implement a richer formatting yourself (with pimp-my-library approach):
Well, if your only problem is making the order of the parameters more flexible, this can be easily done:
And there's also regex replacement with the help of a map:
You might also consider the use of a template engine for really complex and long strings. On top of my head I have Scalate which implements amongst others the Mustache template engine.
Might be overkill and performance loss for simple strings, but you seem to be in that area where they start becoming real templates.
If you're using 2.10 then go with built-in interpolation. Otherwise, if you don't care about extreme performance and are not afraid of functional one-liners, you can use a fold + several regexp scans:
This the answer I came here looking for:
In Scala 2.10 you can use string interpolation.