我有一个Any
类型的变量,其运行时类型为String
,我想将其转换为Int
:
val a: Any = "123"
如果我尝试投射到Int,我会得到例外java.lang.ClassCastException
:
val b = a.asInstanceOf[Int]
那我该怎么做?
答案 0 :(得分:12)
Casting不会转换您的类型,它只是告诉系统您认为自己足够聪明以了解对象的正确类型。例如:
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
您可能正在寻找的是将String
转换为Int
:
val a: Any = "123"
val b = a.asInstanceOf[String].toInt
或者,因为您可以在任何对象上调用toString
:
val b = a.toString.toInt
如果字符串不是有效数字,例如。
,您仍然可以获得运行时异常"foo".toInt // boom!
答案 1 :(得分:2)
通常,您可以避开Scala中的类强制转换和嵌套try catch
块。
import scala.util.{ Try, Failure, Success };
val x: Any = 5;
val myInt = Try { x.toString.toInt) } getOrElse { 0 // or whatever}; // this is defaulting
val mySecondInt = Try { x.toString.toInt };
mySecondInt match {
case Success(theactualInt) => // do stuff
case Failure(e) => // log the exception etc.
}
答案 2 :(得分:0)
scala> val a:Any = "123"
a: Any = 123
scala> val b = a.toString.toInt
b: Int = 123