How can I cast Integer to String in Scala?

ScalaCasting

Scala Problem Overview


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?

Scala Solutions


Solution 1 - Scala

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 - Scala

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 - Scala

An exotic usage of the s String interpolator for code golfers:

val i = 42
s"$i"
// String = 42

Solution 4 - Scala

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.

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionizac89View Question on Stackoverflow
Solution 1 - Scalajanm399View Answer on Stackoverflow
Solution 2 - Scalaom-nom-nomView Answer on Stackoverflow
Solution 3 - ScalaXavier GuihotView Answer on Stackoverflow
Solution 4 - ScalaBlezzView Answer on Stackoverflow