views:

1866

answers:

3

I was wondering what the best way to format a string would be in Scala. I'm reimplementing the toString method for a class, and it's a rather long and complex string. I thought about using String.format but it seems to have problems with Scala. Is there a native Scala function for doing this?

+4  A: 

I was simply using it wrong. Correct usage is .format(parem1, parem2).

Rayne
There is a thing in `RichString` which lets you do some nicer stuff here, though; whereas just using the Java API you do: String.format( "%s has %d bunnies", name, bunnyCount )You can do the following: "%s has %d bunnies".format( name, bunnyCount )Or even use it as an operator: "%s has %d bunnies" format ( name, bunnyCount )
Calum
That's how I'm using it.
Rayne
+1  A: 

The thing to watch out for with String#format is the fact that it is actually implemented using reflection (as of v2.7.4). It delegates to the Java API, but the reflection adds a pretty significant overhead to a comparatively minor method call. You may want to consider Java-style string concatenation, just for performance reasons. As I understand it, Scala version 2.8.0 should resolve this problem.

Daniel Spiewak
The once comically overcomplicated format is now only: def format(args : Any*) : String = java.lang.String.format(self, args.toArray[Any].asInstanceOf[Array[AnyRef]]: _*)
extempore
A: 

How about good old java.text.MessageFormat?

Apocalisp