Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to repeat argument in String format in Scala

How to reuse the same string for format placement? e.g

"%s-%s-%s" format("OK")
>> "OK-OK-OK"
like image 455
Johnny Everson Avatar asked Oct 31 '12 12:10

Johnny Everson


People also ask

What is string * in Scala?

In Scala, as in Java, a string is an immutable object, that is, an object that cannot be modified. On the other hand, objects that can be modified, like arrays, are called mutable objects. Strings are very useful objects, in the rest of this section, we present important methods of java. lang. String class.


2 Answers

This should work:

"%1$s-%1$s-%1$s" format "OK"

The format method of WrappedString uses java.util.Formatter under the hood. And the the Formatter Javadoc says:

The format specifiers for general, character, and numeric types have the following syntax:

%[argument_index$][flags][width][.precision]conversion

The optional argument_index is a decimal integer indicating the position of the argument in the argument list. The first argument is referenced by "1$", the second by "2$", etc.

like image 109
rolve Avatar answered Sep 27 '22 18:09

rolve


"%s-%s-%s".format(Seq.fill(3)("OK"): _*)

The : _* part means "use this sequence as the arguments". Seq.fill(3)("OK") creates three copies of "OK".

like image 40
Rex Kerr Avatar answered Sep 27 '22 18:09

Rex Kerr