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
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
})