27

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?

0

3 Answers 3

42

You can try something like:

val number: Long = 3243
"%d".format(number)
Sign up to request clarification or add additional context in comments.

2 Comments

There's also value in explaining why this should be the case.
.format in this case will be the method of StringLike which is implicitly created from string literal.
22

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)

Comments

7

@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.

2 Comments

This works. Do you know why this won't cause a runtime error like with my RichLong approach?
RichLong is, to Java, just some random class. Java expects to see a boxed primitive integer corresponding to "%d". So of course Java throws a fit when it gets a RichLong. The asInstanceOf[AnyRef] preferentially boxes into the java.lang class, not the Rich class.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.