加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

scala – 简化if(x)Some(y)else?

发布时间:2020-12-16 09:41:24 所属栏目:安全 来源:网络整理
导读:这种常见的模式感觉有点冗长: if (condition) Some(result)else None 我正在考虑使用一个函数来简化: def on[A](cond: Boolean)(f: = A) = if (cond) Some(f) else None 这减少了最大的例子: on (condition) { result } 这样的事情已经存在了吗?还是这个
这种常见的模式感觉有点冗长:

if (condition) 
  Some(result)
else None

我正在考虑使用一个函数来简化:

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

这减少了最大的例子:

on (condition) { result }

这样的事情已经存在了吗?还是这个过度的杀手?

解决方法

Scalaz包括 option功能:

import scalaz.syntax.std.boolean._

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读