简化 if (x) Some(y) else None? [英] Simplify if (x) Some(y) else None?

查看:41
本文介绍了简化 if (x) Some(y) else None?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这种常见的模式感觉有点冗长:

This common pattern feels a bit verbose:

if (condition) 
  Some(result)
else None

我想用一个函数来简化:

I was thinking of using a function to simplify:

def on[A](cond: Boolean)(f: => A) = if (cond) Some(f) else None

这将顶部示例简化为:

on (condition) { result }

这样的东西已经存在了吗?还是这太过分了?

Does something like this exist already? Or is this overkill?

推荐答案

Scalaz 包括 option 函数:

import scalaz.syntax.std.boolean._

true.option("foo") // Some("foo")
false.option("bar") // None

这篇关于简化 if (x) Some(y) else None?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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