开发者

How to format strings in Scala?

开发者 https://www.devze.com 2023-01-21 00:15 出处:网络
I need to print a formatted string containing scala.Long. java.lang.String.format() is incompatible with scala.Long 开发者_StackOverflow(compile time) and RichLong (java.util.IllegalFormatConversionEx

I need to print a formatted string containing scala.Long. java.lang.String.format() is incompatible with scala.Long 开发者_StackOverflow(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?


You can try something like:

val number: Long = 3243
"%d".format(number)


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)


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

0

精彩评论

暂无评论...
验证码 换一张
取 消