views:

164

answers:

3

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)

+8  A: 

You can easily implement a richer formatting yourself (with pimp-my-library approach):

scala> implicit def RichFormatter(string: String) = new {
     |   def richFormat(replacement: Map[String, Any]) =
     |     (string /: replacement) {(res, entry) => res.replaceAll("#\\{%s\\}".format(entry._1), entry._2.toString)}
     | }
RichFormatter: (string: String)java.lang.Object{def richFormat(replacement: Map[String,Any]): String}

scala> "This is #{number} string" richFormat Map("number" -> 1)
res43: String = This is 1 string
Vasil Remeniuk
True, I might even use `%` for that (as in some other languages). But still, it could be a bit more powerful… (Like python’s format maybe.)
Debilski
+12  A: 

Maybe the Scala-Enhanced-Strings-Plugin can help you. Look here:

Scala-Enhanced-Strings-Plugin Documentation

Ruediger Keller
Looks pretty interesting. (Both the docu and the plugin.) But still a bit crazy (also both) because the syntax does not use any delimiters sometimes…
Debilski
I'm using it in production and it's great! Delimiters are only required when the expression to be interpolated has much syntax beyond just a variable name.
Alex Cruise
+2  A: 

Well, if your only problem is making the order of the parameters more flexible, this can be easily done:

scala> "%d %d" format (1, 2)
res0: String = 1 2

scala> "%2$d %1$d" format (1, 2)
res1: String = 2 1

And there's also regex replacement with the help of a map:

scala> val map = Map("number" -> 1)
map: scala.collection.immutable.Map[java.lang.String,Int] = Map((number,1))

scala> val getGroup = (_: scala.util.matching.Regex.Match) group 1
getGroup: (util.matching.Regex.Match) => String = <function1>

scala> val pf = getGroup andThen map.lift andThen (_ map (_.toString))
pf: (util.matching.Regex.Match) => Option[java.lang.String] = <function1>

scala> val pat = "#\\{([^}]*)\\}".r
pat: scala.util.matching.Regex = #\{([^}]*)\}

scala> pat replaceSomeIn ("This is #{number} string", pf)
res43: String = This is 1 string
Daniel