如何在一行中将 Some(" ") 转换为 None? [英] How to convert a Some(" ") to None in one-line?

查看:41
本文介绍了如何在一行中将 Some(" ") 转换为 None?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想定义一个函数:

def convert(x: Option[String]): Option[String] = ...

xSome(str)且修剪后str为空时,会转为None,否则,将是一个带有修剪字符串的 Some.

When x is Some(str) and the str is empty after trimming, it will be converted to a None, otherwise, it will be a Some with trimmed string.

因此,测试用例将是:

convert(Some("")) == None
convert(Some("  ")) == None
convert(None) == None
convert(Some(" abc ")) == Some("abc")

我可以写成:

def convert(x: Option[String]): Option[String] = x match {
  case Some(str) if str.trim()!="" => Some(str.trim())
  case _ => None
}

但我希望找到一个更简单的实现(一行).

But I hope to find a simpler implementation(one-line).

推荐答案

这个怎么样:

def convert(x: Option[String]) = 
    x.map(_.trim()).filterNot(_.isEmpty())

更新:@JamesMoore@PeterSchmitz 建议的替代语法:

UPDATE: Alternative syntaxes suggested by @JamesMoore and @PeterSchmitz:

x map {_.trim} filterNot {_.isEmpty}
x map (_.trim) filterNot (_.isEmpty)

这篇关于如何在一行中将 Some(" ") 转换为 None?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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