在 Scala 中“转换”Option[x] 到 x
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19765713/
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
“Convert” Option[x] to x in Scala
提问by mahoosh
I working with play for scala (2.1) and I need to convert an "Option[Long]" value to "Long".
我使用 play for scala (2.1),我需要将“Option[Long]”值转换为“Long”。
I know how to do the opposite, I mean:
我知道如何做相反的事情,我的意思是:
def toOption[Long](value: Long): Option[Long] = if (value == null) None else Some(value)
But in my case, I have to pass a value of "Option[Long]" as a type into a method that takes "Long". Any help please.
但就我而言,我必须将“Option[Long]”的值作为类型传递给采用“Long”的方法。请任何帮助。
回答by Dao Lam
If you have x as Option[Long], x.getwill give you Long.
如果你有 x 作为 Option[Long],x.get会给你 Long。
回答by Travis Brown
First of all, your implementation of "the opposite" has some serious problems. By putting a type parameter named Longon the method you're shadowing the Longtype from the standard library. You probably mean the following instead:
首先,你的“相反”的实现有一些严重的问题。通过Long在方法上放置一个命名的类型参数,您将隐藏Long标准库中的类型。您可能是指以下内容:
def toOption(value: Long): Option[Long] =
if (value == null) None else Some(value)
Even this is kind of nonsensical (since scala.Longis not a reference type and can never be null), unless you're referring to java.lang.Long, which is a recipe for pain and confusion. Finally, even if you were dealing with a reference type (like String), you'd be better off writing the following, which is exactly equivalent:
即使这有点荒谬(因为scala.Long它不是引用类型并且永远不会是null),除非您指的是java.lang.Long,这是痛苦和困惑的秘诀。最后,即使您正在处理引用类型(如String),您最好编写以下内容,这完全等效:
def toOption(value: String): Option[String] = Option(value)
This method will return Noneif and only if valueis null.
None当且仅当valueis 时,此方法才会返回null。
To address your question, suppose we have the following method:
为了解决您的问题,假设我们有以下方法:
def foo(x: Long) = x * 2
You shouldn't generally think in terms of passing an Option[Long]to foo, but rather of "lifting" foointo the Optionvia map:
您通常不应该考虑传递Option[Long]to foo,而是“提升”foo到Optionvia map:
scala> val x: Option[Long] = Some(100L)
x: Option[Long] = Some(100)
scala> x map foo
res14: Option[Long] = Some(200)
The whole point of Optionis to model (at the type level) the possibility of a "null" value in order to avoid a whole class of NullPointerException-y problems. Using mapon the Optionallows you to perform computations on the value that may be in the Optionwhile continuing to model the possibility that it's empty.
重点Option是对(在类型级别)“空”值的可能性进行建模,以避免整类NullPointerException-y 问题。使用maponOption允许您对可能存在的值执行计算,Option同时继续对其为空的可能性进行建模。
As another answer notes, it's also possible to use getOrElseto "bail out" of the Option, but this usually isn't the idiomatic approach in Scala (except in cases where there really is a reasonable default value).
正如另一个答案所指出的,也可以使用getOrElse来“拯救” Option,但这通常不是 Scala 中的惯用方法(除非确实存在合理的默认值)。
回答by Andreas Neumann
This method is already defined on Option[A] and is called get:
此方法已在 Option[A] 上定义并称为get:
scala> val x = Some(99L)
x: Some[Long] = Some(99)
scala> x.get
res0: Long = 99
The problem is that calling get on None will throw a NoSucheElement Exception:
问题是在 None 上调用 get 会抛出一个 NoSucheElement 异常:
scala> None.get
java.util.NoSuchElementException: None.get
thus you will not gain any benefits from using an Option type.
因此,您不会从使用 Option 类型中获得任何好处。
Thus as stated before you can use getOrElseif you can provide a sensible default value or handle the Exception.
因此,如前所述,如果您可以提供合理的默认值或处理异常,则可以使用getOrElse。
The idiomatic scala way would be using map or a for-comprehension
惯用的 Scala 方式是使用 map 或 for-comprehension
x map (_ + 1)
res2: Option[Long] = Some(100)
or
或者
for (i <- x) yield i +1
res3: Option[Long] = Some(100)
回答by Yuriy
Option is way to localise side-effect (your function can return empty value). And good style to lift your computation to Option (Option is Monad with map& flatMapmethods).
Option 是本地化副作用的方法(您的函数可以返回空值)。以及将您的计算提升到 Option 的良好风格(Option 是具有map和flatMap方法的Monad )。
val x = Option[Long](10)
x.map { a => a + 10 }
And extract value with manually processing of side effect:
并通过手动处理副作用提取值:
val res = x match {
case Some(a) => s"Value: $a"
case None => "no value"
}
回答by 0__
You need to decide what happens when the option is None. Do you provide a default value?
您需要决定选项时会发生什么None。你提供默认值吗?
def unroll(opt: Option[Long]): Long = opt getOrElse -1L // -1 if undefined
unroll(None) // -> -1
You could also throw an exception:
你也可以抛出异常:
def unroll(opt: Option[Long]): Long = opt.getOrElse(throw
new IllegalArgumentException("The option is expected to be defined at this point")
)
unroll(None) // -> exception
In case, refrain from using null, unless you have very good reasons to use it (opt.orNull).
在这种情况下,不要使用null,除非您有充分的理由使用它 ( opt.orNull)。
回答by Christopher Hunt
As has already been mentioned getOrElse is probably what you're looking for in answering your question directly.
正如已经提到的那样, getOrElse 可能是您直接回答问题时所寻找的。
Please note also that to convert to an option you can simply:
另请注意,要转换为选项,您只需:
val myOption = Option(1)
myOption will now be Some(1)
myOption 现在将是 Some(1)
val myOption = Option(null)
myOption will now be None.
myOption 现在将是 None。

