Scala - “if(true) Some(1)"无需输入“else None" [英] Scala - "if(true) Some(1)" without having to type "else None"

查看:23
本文介绍了Scala - “if(true) Some(1)"无需输入“else None"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在scala中,如果你有一个Option,你可以通过做oldOption.map(_.something)得到另一个Option.我想要做的是取一个布尔值并做同样的事情.换句话说,我想要以下内容的简写:

In scala, if you have an Option, you can get another Option by doing oldOption.map(_.something). What I want to do is take a boolean and do the same thing. In other words, I want shorthand for the following:

if(someCondition)
  Some(data)
else
  None

有没有一种惯用的方法可以从这样的布尔值中获取 Option 而不必执行else None"?

Is there an idiomatic way to get an Option out of a Boolean like this without having to do "else None"?

推荐答案

Scalaz 有这个.代码如下所示:

Scalaz has this. The code would look like this:

import scalaz._
import Scalaz._
val b = true  
val opt = b option "foo"

opt 的类型将是 Option[String]

这篇关于Scala - “if(true) Some(1)"无需输入“else None"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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