Cast Option[Any] to int

后端 未结 3 576
小蘑菇
小蘑菇 2021-01-03 19:37

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

3条回答
  •  心在旅途
    2021-01-03 20:05

    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.

提交回复
热议问题