69

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?

2
  • 11
    Technically, you cannot. Casting is only a reinterpretation of a value to a different but compatible type. It always succeeds if casting to a more general type than the statically known type of the value. It can fail dynamically if casting to a type that the value could have but does not and is rejected by the compiler if the type to which the value is being cast is neither a supertype nor a subtype of the statically known type. Int vs. String falls into the latter category. Commented Jun 1, 2013 at 17:06
  • 3
    The correct way to phrase the question would be "How can I convert an Int to a String in Scala?" I can imagine where the question comes from: in Java, ints are not objects, so you need some other mechanism to perform the conversion. In Scala, everything is an object (yay!), so you don't need such special-case mechanisms; toString is the way to convert anything to a String. Commented Jun 2, 2013 at 23:28

4 Answers 4

119

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.

Sign up to request clarification or add additional context in comments.

2 Comments

@janm How do I specify the radix?
@Sohaib x.toHexString or f"$x%x", x.toOctalString or f"$x%o" - see docs.oracle.com/javase/6/docs/api/java/util/…
7

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

Comments

5

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

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

Comments

0

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.

1 Comment

This would be an abuse of implicit conversions because it erodes type safety

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.