Scala使多个选项检查更加简洁 [英] Scala make multiple option checks more concise
本文介绍了Scala使多个选项检查更加简洁的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Scala和Play框架中使用选项,是否有更简洁的方法来检查x数量的变量?
Working with Options in Scala and Play Framework, is there a more concise way of checking x amount of variables like so?
if (a.isDefined || b.isDefined || c.isDefined || d.isDefined ...) {
}
有可能像(a,b,c,d).isDefined
这样的班轮吗?
Is a one liner something like (a,b,c,d).isDefined
possible?
谢谢
推荐答案
在我的头顶上,也许有一个更好的方法:
On top of my head, probably there's a nicer way:
List(a, b, c, d).exists(_.isDefined)
对于and
(来自Rob Starling的评论):
For and
s (from Rob Starling comment):
List(a, b, c, d).forall(_.isDefined)
您还可能具有更复杂的条件组成:
You could also have more complex condition compositions:
// (a || b) && (c || d)
List(
List(a, b).exists(_.isDefined),
List(c, d).exists(_.isDefined)
).forall(identity)
// (a && b) || (c && d)
List(
List(a, b).forall(_.isDefined),
List(c, d).forall(_.isDefined)
).exists(identity)
以此类推.
这篇关于Scala使多个选项检查更加简洁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文