如果已填充,则将列表转换为选项 [英] Convert a List into an Option if it is populated
本文介绍了如果已填充,则将列表转换为选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个方法可以将列表转换为对象的 Option
,如果列表为空,则转换为 None
.
I have a method that should convert a list to an Option
of an object, or None
if the list is empty.
def listToOption(myList: List[Foo]): Option[Bar] = {
if(myList.nonEmpty) Some(Bar(myList))
else None
}
case class Bar(fooList: List[Foo]) {}
出于某种原因,我的解决方案感觉相当不优雅,而不是 Scala 方式.看起来我应该能够使用 List
上的方法来做这种事情,但我无法理解它.
For some reason, my solution feels rather inelegant, and not the Scala way. It seems I should be able to use a method on List
to do this sort of thing, but I can't wrap my head around it.
有没有更像 Scala 的方法来做到这一点?
Is there a more Scala-like way to do this?
推荐答案
Lee 的回答很好,但我认为这更符合意图:
Lee's answer is good, but I think this corresponds to the intention a bit more clearly:
Option(myList).filter(_.nonEmpty).map(Bar)
这篇关于如果已填充,则将列表转换为选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文