简体   繁体   English

将选项[Any]转换为int

[英]Cast Option[Any] to int

How do I cast this to an Int and not Some(Int) 如何将其转换为Int而不是Some(Int)

val a: Option[Any] = Some(1)

I tried toInt and it gave an error value toInt is not a member of Option[Any] 我试过toInt并且它给出了一个错误value toInt is not a member of Option[Any]

You could do a.get.asInstanceOf[Int] however it is unsafe. 你可以做a.get.asInstanceOf[Int]然而它是不安全的。 A better way would be to retain the type information ie using a Option[Int] instead of an Option[Any] . 更好的方法是保留类型信息,即使用Option[Int]而不是Option[Any] Then you would not need to cast the result with asInstanceOf . 然后你不需要使用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. 直接使用get是不安全的,因为如果OptionNone ,则抛出异常。 So using getOrElse is safer. 因此使用getOrElse更安全。 Or you could use pattern matching on a to get the value. 或者您可以在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
})

Using .asInstanceOf method 使用.asInstanceOf方法

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. 我必须注意,这是不安全的强制转换:如果你的选项不包含Int,你将获得运行时异常。

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. 如果你进行了强制转换,你可能会将一个潜在的编译时错误(我们喜欢它,因为它很容易解决)转换为ClassCastException,我们不喜欢它,因为它发生在运行时。 If you need to use casts in Scala, very likely you are using an improper pattern. 如果你需要在Scala中使用强制转换,很可能你使用的是不正确的模式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM