I need some enlightenment about the guard in a for loop in Scala: my code is
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.
Can someone tell me a decent way to do it?
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 ???