[英]Scala: Conditional guard in for loop
I need some enlightenment about the guard in a for loop in Scala: my code is 我需要对Scala的for循环中的后卫有所启发:我的代码是
for {
enterprise <- itr
preferName <- enterprise \* qpreferedName
variantName <- enterprise \* qvariantName
attrVRes <- enterprise \* qtype \@ attrRes
if (text(preferName).contains(keyword) || text(variantName).contains(keyword))
} {
//loop code
}
Now it works file. 现在可以正常工作了。 But I want to check the value of
keyword
, if it's an empty string, I will not apply this guard ( if (text(preferName).contains(keyword) || text(variantName).contains(keyword))
), otherwise apply it. 但是我想检查
keyword
的值,如果它是一个空字符串,我将不应用此保护( if (text(preferName).contains(keyword) || text(variantName).contains(keyword))
),否则适用它。
Can someone tell me a decent way to do it? 有人可以告诉我一种不错的方法吗?
Since it seems that keyword
is defined outside of the for comprehension, I would set up a boolean out there, then add it into the guard. 由于似乎
keyword
是在for理解之外定义的,所以我将在那里设置一个布尔值,然后将其添加到防护中。 Eg: 例如:
val keywordInvalid = keyword.isEmpty // Or however you want to define your condition
for {
enterprise <- itr
preferName <- enterprise \* qpreferedName
variantName <- enterprise \* qvariantName
attrVRes <- enterprise \* qtype \@ attrRes
if keywordInvalid || text(preferName).contains(keyword) || text(variantName).contains(keyword)
} {
//loop code
}
Or flip it (as per @Łukasz's comment): 或翻转它(根据@Łukasz的评论):
val keywordValid = keyword.nonEmpty
...
for {
...
if keywordValid && ((text(preferName).contains(keyword) || text(variantName).contains(keyword))
} {
//loop code
}
You can define such utility 您可以定义这样的实用程序
def textContains(str: String): String => Boolean = str match {
case "" => Function.const(true)
case _ => text(_).contains(str)
}
and use it as 并用作
for {
/* ... */
if Seq(preferName,variantName).exists(textContains(keyword))
} yield ???
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.