如何在 Scala 中格式化字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3989243/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to format strings in Scala?
提问by Basilevs
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)
我需要打印一个包含 scala.Long 的格式化字符串。java.lang.String.format() 与 scala.Long(编译时)和 RichLong(java.util.IllegalFormatConversionException)不兼容
Compiler warns about deprecation of Integer on the following working code:
编译器在以下工作代码中警告弃用 Integer:
val number:Long = 3243
String.format("%d", new java.lang.Long(number))
Should I change fomatter, data type or something else?
我应该更改格式化程序、数据类型还是其他内容?
回答by Bruno Reis
You can try something like:
您可以尝试以下操作:
val number: Long = 3243
"%d".format(number)
回答by Kevin Wright
The format method in Scala exists directly on instancesof String, so you don't need/want the static class method. You also don't need to manually box the longprimitive, let the compiler take care of all that for you!
Scala 中的 format 方法直接存在于String 的实例上,因此您不需要/不需要静态类方法。您也不需要手动装箱long原语,让编译器为您处理所有这些!
String.format("%d", new java.lang.Integer(number))
is therefore better written as
因此最好写成
"%d".format(number)
回答by Rex Kerr
@Bruno's answer is what you should use in most cases.
@Bruno 的答案是您在大多数情况下应该使用的答案。
If you must use a Java method to do the formatting, use
如果必须使用 Java 方法进行格式化,请使用
String.format("%d",number.asInstanceOf[AnyRef])
which will box the Longnicely for Java.
这将Long很好地为 Java装箱。

