How can I cast Integer to String in Scala?
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?
Solution 1:
If you have variable x
of type Int
, you can call toString
on it to get its string representation.
val x = 42
x.toString // gives "42"
That gives you the string. Of course, you can use toString
on any Scala "thing"--I'm avoiding the loaded object
word.
Solution 2:
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
Solution 3:
An exotic usage of the s
String interpolator for code golfers:
val i = 42
s"$i"
// String = 42