Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast Any of String to Int

Tags:

scala

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?

like image 898
Incerteza Avatar asked Nov 15 '13 16:11

Incerteza


People also ask

Can we convert string to int in java?

The method generally used to convert String to Integer in Java is parseInt() of String class.

How can a string be converted to a number?

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.

Can you cast a string to an int in C++?

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.


2 Answers

scala> val a:Any = "123"
a: Any = 123

scala> val b = a.toString.toInt
b: Int = 123
like image 30
djcastr0 Avatar answered Sep 28 '22 23:09

djcastr0


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!
like image 133
0__ Avatar answered Sep 29 '22 00:09

0__