I have a variable of type Any
with runtime type of String
which I want to cast to Int
:
val a: Any = "123"
If I try to cast in to Int, I'll get an exception java.lang.ClassCastException
:
val b = a.asInstanceOf[Int]
How do I do that then?
The method generally used to convert String to Integer in Java is parseInt() of String class.
You convert a string to a number by calling the Parse or TryParse method found on numeric types ( int , long , double , and so on), or by using methods in the System. Convert class. It's slightly more efficient and straightforward to call a TryParse method (for example, int.
One effective way to convert a string object into a numeral int is to use the stoi() function. This method is commonly used for newer versions of C++, with is being introduced with C++11. It takes as input a string value and returns as output the integer version of it.
scala> val a:Any = "123"
a: Any = 123
scala> val b = a.toString.toInt
b: Int = 123
Casting doesn't convert your type, it simply tells the system that you think you are smart enough to know the proper type of an object. For example:
trait Foo
case class Bar(i: Int) extends Foo
val f: Foo = Bar(33)
val b = f.asInstanceOf[Bar] // phew, it works, it is indeed a Bar
What you are probably looking for is to convert a String
to an Int
:
val a: Any = "123"
val b = a.asInstanceOf[String].toInt
Or, since you can call toString
on any object:
val b = a.toString.toInt
You can still get a runtime exception if the string is not a valid number, e.g.
"foo".toInt // boom!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With