Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast Option[Any] to int

Tags:

scala

How do I cast this to an Int and not Some(Int)

val a: Option[Any] = Some(1)

I tried toInt and it gave an error value toInt is not a member of Option[Any]

like image 741
Bob Avatar asked Jul 30 '12 05:07

Bob


3 Answers

You could do a.get.asInstanceOf[Int] however it is unsafe. A better way would be to retain the type information i.e. using a Option[Int] instead of an Option[Any]. Then you would not need to cast the result with asInstanceOf.

val a:Option[Int] = Some(1)
val i = a.get

Using get directly is unsafe since if the Option is a None an exception is thrown. So using getOrElse is safer. Or you could use pattern matching on a to get the value.

val a:Option[Any] = Some(1) // Note using Any here
val i = (a match {
  case Some(x:Int) => x // this extracts the value in a as an Int
  case _ => Int.MinValue
})
like image 74
Emil H Avatar answered Oct 18 '22 00:10

Emil H


Using .asInstanceOf method

a.getOrElse(0).asInstanceOf[Int]

I have to note that this is unsafe cast: if your Option contains not Int, you'll get runtime exception.

like image 28
om-nom-nom Avatar answered Oct 17 '22 23:10

om-nom-nom


The reason why you can't cast it is because you are not supposed to cast. While static typed programming languages allows you to manually cast between one type and the other, the best suggestion I can give you is to forget about this features.

In particularly, if you want to get the best out of each programming language, try to make a proper user, and if a language does not fit the usage you want just choose another one (such as a dynamically typed one):

If you make casts you turn a potential compile time error, which we like because it's easy to solve, into a ClassCastException, which we don't like because it occurs at runtime. If you need to use casts in Scala, very likely you are using an improper pattern.

like image 3
Edmondo1984 Avatar answered Oct 17 '22 22:10

Edmondo1984