简体   繁体   English

如果Option不包含任何内容或包含不需要的类型,则通常返回None

[英]Idiomatically return None if Option contains None or contains unwanted type

I want to read the head of an possibly empty list and if that head contains a specific pattern I will return Some() , in all other cases I want to return None. 我想读取一个可能为空的列表的头部,如果该头部包含特定模式,我将返回Some() ,在所有其他情况下,我都将返回None。

Here is my working code, but it's a bit ugly with the nested matches and re-wrapping the object in a Some() after unwrapping it. 这是我的工作代码,但是嵌套的匹配项有点丑陋,在解开对象后将其重新包裹在Some()中。

 list.headOption match{
  case None => None
  case Some(csvString) => csvString.split(',') match {
    case Array(a, b, c) => Some(Array(a, b, c))
    case _ => None
  }
}

Is there a nicer, more idiomatic way of achieving this? 有没有更好,更惯用的方式来实现这一目标?

Using map and collect you can do 使用mapcollect您可以做

list.headOption.map(_.split(',')).collect {
  case values @ Array(a, b, c) => values
}

In this particular case you may use .map : 在这种情况下,您可以使用.map

list.headOption.map(_.split(','))

And if you need to make sure the array has only 3 elements, you can use a combination of .map and .filter : 而且,如果需要确保数组只有3个元素,则可以使用.map.filter的组合:

list.headOption.map(_.split(',')).filter(_.length == 3)

Or test a specific pattern: 或测试特定模式:

list.headOption.map(_.split(',')).filter {
  case Array(a, b, c) => true
  case _ => false
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM