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
2009-05-12 23:35:25
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
2009-05-15 14:13:57
That's how I'm using it.
Rayne
2009-05-16 01:35:29
+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
2009-05-13 03:12:58
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
2009-05-14 21:02:37