当一个选项为非空时执行某项操作 [英] Do something when exactly one option is non-empty
本文介绍了当一个选项为非空时执行某项操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果两个选项之一恰好是非空的,我想计算一些东西。显然,这可以通过模式匹配来完成,但是还有更好的方法吗?
I want to compute something if exactly one of two options is non-empty. Obviously this could be done by a pattern match, but is there some better way?
(o1, o2) match {
case (Some(o), None) => Some(compute(o))
case (None, Some(o)) => Some(compute(o))
case _ => None
}
推荐答案
您可以执行以下操作
if (o1.isEmpty ^ o2.isEmpty)
List(o1,o2).flatMap(_.map(x=>Some(compute(x)))).head
else
None
但是模式匹配可能是更好的方法。
But pattern matching is probably the better way to go.
这篇关于当一个选项为非空时执行某项操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文