在 Scala 中“转换"Option[x] 到 x [英] “Convert” Option[x] to x in Scala

查看:22
本文介绍了在 Scala 中“转换"Option[x] 到 x的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为 Scala (2.1) 使用 play,我需要将Option[Long]"值转换为Long".

I working with play for scala (2.1) and I need to convert an "Option[Long]" value to "Long".

我知道如何做相反的事情,我的意思是:

I know how to do the opposite, I mean:

  def toOption[Long](value: Long): Option[Long] = if (value == null) None else Some(value)

但就我而言,我必须将Option[Long]"的值作为类型传递给采用Long"的方法.请任何帮助.

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.

推荐答案

首先,你的相反"的实现有一些严重的问题.通过在方法上放置一个名为 Long 的类型参数,您将隐藏标准库中的 Long 类型.您可能指的是以下内容:

First of all, your implementation of "the opposite" has some serious problems. By putting a type parameter named Long on the method you're shadowing the Long type from the standard library. You probably mean the following instead:

def toOption(value: Long): Option[Long] =
  if (value == null) None else Some(value)

即使这有点荒谬(因为 scala.Long 不是引用类型并且永远不可能是 null),除非您指的是 java.lang.Long,这是痛苦和困惑的秘诀.最后,即使您正在处理引用类型(如 String),您最好编写以下内容,这完全等效:

Even this is kind of nonsensical (since scala.Long is 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:

def toOption(value: String): Option[String] = Option(value)

当且仅当 valuenull 时,此方法将返回 None.

This method will return None if and only if value is null.

为了解决您的问题,假设我们有以下方法:

To address your question, suppose we have the following method:

def foo(x: Long) = x * 2

您通常不应该考虑将 Option[Long] 传递给 foo,而是提升"fooOption 通过 map:

You shouldn't generally think in terms of passing an Option[Long] to foo, but rather of "lifting" foo into the Option via map:

scala> val x: Option[Long] = Some(100L)
x: Option[Long] = Some(100)

scala> x map foo
res14: Option[Long] = Some(200)

Option 的全部意义在于对(在类型级别)空"值的可能性进行建模,以避免出现一整类 NullPointerException-y问题.在 Option 上使用 map 允许您对 Option 中可能存在的值执行计算,同时继续对其为空的可能性进行建模.

The whole point of Option is to model (at the type level) the possibility of a "null" value in order to avoid a whole class of NullPointerException-y problems. Using map on the Option allows you to perform computations on the value that may be in the Option while continuing to model the possibility that it's empty.

作为另一个答案,也可以使用 getOrElse 来拯救"Option,但这通常不是 Scala 中的惯用方法(除了在确实存在合理默认值的情况下).

As another answer notes, it's also possible to use getOrElse to "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).

这篇关于在 Scala 中“转换"Option[x] 到 x的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆