Convert java.lang.String string to Scala string

I have a line in my Scala program that I would like to use as Int.

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

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

I know that 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 java.lang.String . I heard that a Scala String is just a wrapper around java.lang.String , but I have not found clear documentation on how to drop to a Scala string.

Is there some kind of function that I can use, for example:

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

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

+6
source share
3 answers

This is not a wrapper, but in fact java.lang.String. No need for additional problems:

 ยป 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 
+9
source

java.lang.String implicitly modified using Scala-specific string methods, so manual conversion is not required.

+2
source

Use asInstanceOf [String] to parse a Java string to a Scala string.

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

Source: https://habr.com/ru/post/969703/


All Articles