scala 将 Option[Any] 转换为 int
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11716081/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Cast Option[Any] to int
提问by Bob
How do I cast this to an Int and not Some(Int)
我如何将它转换为 Int 而不是 Some(Int)
val a: Option[Any] = Some(1)
I tried toIntand it gave an error value toInt is not a member of Option[Any]
我试过了toInt,它给出了一个错误value toInt is not a member of Option[Any]
回答by Emil H
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.
你可以这样做,a.get.asInstanceOf[Int]但它是不安全的。更好的方法是保留类型信息,即使用 aOption[Int]而不是Option[Any]。那么你就不需要用asInstanceOf.
val a:Option[Int] = Some(1)
val i = a.get
Using getdirectly is unsafe since if the Optionis a Nonean exception is thrown. So using getOrElseis safer. Or you could use pattern matching on ato get the value.
get直接使用是不安全的,因为如果Option是一个None异常会被抛出。所以使用getOrElse更安全。或者您可以使用模式匹配a来获取值。
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
})
回答by om-nom-nom
Using .asInstanceOfmethod
使用.asInstanceOf方法
a.getOrElse(0).asInstanceOf[Int]
I have to note that this is unsafecast: if your Option contains not Int, you'll get runtime exception.
我必须注意,这是不安全的转换:如果您的 Option 不包含 Int,您将获得运行时异常。
回答by Edmondo1984
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.
如果您进行强制转换,则会将潜在的编译时错误(我们喜欢它,因为它很容易解决)转化为 ClassCastException,我们不喜欢它,因为它发生在运行时。如果您需要在 Scala 中使用强制转换,很可能您使用了不正确的模式。

