Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Any to Integer in Scala?

How do I convert an Any to an Integer?

Specifically, I have a function that returns Any, and in one situation I know it will return a number of type Any, and I need that number to be converted to type Integer so I can use it in another function.

like image 936
user7804781 Avatar asked Aug 01 '17 10:08

user7804781


People also ask

How do I convert a string to an int in Scala?

A string can be converted to integer in Scala using the toInt method. This will return the integer conversion of the string. If the string does not contain an integer it will throw an exception with will be NumberFormatException.

What is asInstanceOf in Scala?

In Dynamic Programming Languages like Scala, it often becomes necessary to cast from type to another. Type Casting in Scala is done using the asInstanceOf[] method. Applications of asInstanceof method. This perspective is required in manifesting beans from an application context file.

How do I convert a string to a char in Scala?

The toCharArray() method is utilized to convert a stated string to CharArray. Return Type: It returns CharArray.


1 Answers

Your function is likely designed very poorly. 99% of the time there is a better way, then just returning Any from an API entry point.

If you insist on having to deal with Any, a safe way to convert it to an int would be something like this:

def toInt(x: Any): Option[Int] = x match {
  case i: Int => Some(i)
  case _ => None
}
like image 86
Dima Avatar answered Sep 26 '22 08:09

Dima