如何在 Scala 中将整数转换为字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16874334/
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 can I cast Integer to String in Scala?
提问by user2162550
I searched for a while the answer to this question but came out empty. What is the simple command of casting variable X which is Integer, to a String?
我搜索了一段时间这个问题的答案,但结果是空的。将整数变量 X 转换为字符串的简单命令是什么?
回答by janm399
If you have variable xof type Int, you can call toStringon it to get its string representation.
如果你有xtype 的变量Int,你可以调用toString它来获取它的字符串表示。
val x = 42
x.toString // gives "42"
That gives you the string. Of course, you can use toStringon any Scala "thing"--I'm avoiding the loaded objectword.
这给了你字符串。当然,您可以toString在任何 Scala“事物”上使用——我避免使用加载的object词。
回答by om-nom-nom
Is it simple enough?
够简单吗?
scala> val foo = 1
foo: Int = 1
scala> foo.toString
res0: String = 1
scala> val bar: java.lang.Integer = 2
bar: Integer = 2
scala> bar.toString
res1: String = 2
回答by Xavier Guihot
An exotic usage of the sString interpolatorfor code golfers:
代码高尔夫球手的s字符串插值器的奇特用法:
val i = 42
s"$i"
// String = 42
回答by Blezz
I think for this simple us case invoking toString method on an Int is the best solution, however it is good to know that Scala provides more general and very powerful mechanism for this kind of problems.
我认为对于这个简单的用例,在 Int 上调用 toString 方法是最好的解决方案,但是很高兴知道 Scala 为此类问题提供了更通用且非常强大的机制。
implicit def intToString(i: Int) = i.toString
def foo(s: String) = println(s)
foo(3)
Now you can treat Int as it was String (and use it as an argument in methods which requires String), everything you have to do is to define the way you convert Int to String.
现在您可以将 Int 视为 String(并在需要 String 的方法中将其用作参数),您需要做的一切就是定义将 Int 转换为 String 的方式。

