Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format strings in Scala?

Tags:

scala

I need to print a formatted string containing scala.Long. java.lang.String.format() is incompatible with scala.Long (compile time) and RichLong (java.util.IllegalFormatConversionException)

Compiler warns about deprecation of Integer on the following working code:

val number:Long = 3243
String.format("%d", new java.lang.Long(number))

Should I change fomatter, data type or something else?

like image 319
Basilevs Avatar asked Oct 21 '10 15:10

Basilevs


People also ask

How can you format a string in Scala?

In Scala Formatting of strings can be done utilizing two methods namely format() method and formatted() method. These methods have been approached from the Trait named StringLike.

What is string interpolation in Scala?

String Interpolation refers to substitution of defined variables or expressions in a given String with respected values. String Interpolation provides an easy way to process String literals. To apply this feature of Scala, we must follow few rules: String must be defined with starting character as s / f /raw.

How do you add a variable to a string in Scala?

To use basic string interpolation in Scala, precede your string with the letter s and include your variables inside the string, with each variable name preceded by a $ character.

What is stripMargin in Scala?

stripMargin ( '#' ) All of these approaches yield the same result, a multiline string with each line of the string left justified: Four score and seven years ago. This results in a true multiline string, with a hidden \n character after the word “and” in the first line.


3 Answers

You can try something like:

val number: Long = 3243 "%d".format(number) 
like image 101
Bruno Reis Avatar answered Sep 22 '22 06:09

Bruno Reis


The format method in Scala exists directly on instances of String, so you don't need/want the static class method. You also don't need to manually box the long primitive, let the compiler take care of all that for you!

String.format("%d", new java.lang.Integer(number)) 

is therefore better written as

"%d".format(number) 
like image 27
Kevin Wright Avatar answered Sep 19 '22 06:09

Kevin Wright


@Bruno's answer is what you should use in most cases.

If you must use a Java method to do the formatting, use

String.format("%d",number.asInstanceOf[AnyRef])

which will box the Long nicely for Java.

like image 26
Rex Kerr Avatar answered Sep 22 '22 06:09

Rex Kerr