将 Option[Any] 转换为 int [英] Cast Option[Any] to int
问题描述
如何将其转换为 Int 而不是 Some(Int)
How do I cast this to an Int and not Some(Int)
val a: Option[Any] = Some(1)
我尝试了 toInt
并且它给出了一个错误 value toInt is not a member of Option[Any]
I tried toInt
and it gave an error value toInt is not a member of Option[Any]
推荐答案
你可以做 a.get.asInstanceOf[Int]
但是它是不安全的.更好的方法是保留类型信息,即使用 Option[Int]
而不是 Option[Any]
.那么你就不需要用 asInstanceOf
来转换结果.
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
直接使用 get
是不安全的,因为如果 Option
是 None
会抛出异常.所以使用 getOrElse
更安全.或者您可以在 a
上使用模式匹配来获取值.
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
})
这篇关于将 Option[Any] 转换为 int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!