8

I have a String in my Scala program that I'd like to cast as an Int.

def foo(): Int = x.getTheNumericString().toInt

The problem is that x.getTheNumericString() comes from a Java library and returns a java.lang.String, which doesn't have a toInt method.

I know I can create a Scala string with val s: String = "123", but I noticed that when I create a string like val t = "456" I get a java.lang.String. I have heard that Scala String is just a wrapper around java.lang.String, but I haven't found any clear documentation on how to cast to the Scala string.

Is there some function I can use like:

def foo(): Int = f(x.getTheNumericString()).toInt

As it stands now, my compiler complains about the original definition value toInt is not a member of String

3 Answers 3

11

It's not a wrapper, but actually java.lang.String. No need in additional hassle:

» touch 123
» scala
...

val foo = new java.io.File("123")
// java.io.File = 123

// Get name is a java api, which returns Java string

foo.getName.toInt
// res2: Int = 123
Sign up to request clarification or add additional context in comments.

11 Comments

To back this up, check the source of Predef out: github.com/scala/scala/blob/v2.11.1/src/library/scala/…
@gpampara this will require an additional comment, stating that type will be substituted at compile time and leaves no actual traces in resulting bytecode
I wish that were true, but my compiler complains that toInt is not a member of String
@usmcs which version of Scala are you using?
2.10.1 in Intellij 13.0.1
|
4

java.lang.String is implicitly amended with Scala specific string methods so no manual conversion should be necessary.

Comments

0

Use asInstanceOf[String] to syntactically convert Java string to Scala string.

val str: String = "java_string".asInstanceOf[String]

Comments

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.