如何迭代scala中的每个状态



我正在尝试遍历每个状态,以检查ArrayList是否至少有1个ACTIVE和1个INACTIVE状态。

var active = false;
var inactive = false;
for (item <- reasons.items) {
if(item.status == "ACTIVE")
active = true
if(item.status == "INACTIVE")
}
active must be (true)
inactive must be (true)

有更干净的方法吗?我试过这样的流,但没有运气

var active = false;      
var stream = reasons.items.toStream
.forEach(item => if(item.status == "ACTIVE") {active = true})

注:原因包含项(共1项(。items包含单独的项目,可以称为类似的原因。items.get(x(.

其他答案很好地解释了如何使用Scala集合实现这一点。由于看起来您正在使用ScalaTest,我想补充一点,您也可以使用ScalaTest在元素上循环。

使用来自检查器的循环样式语法:

forAtLeast(1, reasons.items) { item =>
item.status must be ("ACTIVE")
}
forAtLeast(1, reasons.items) { item =>
item.status must be ("INACTIVE")
}

请注意,检查器是与匹配器分开定义的,因此必须使用import org.scalatest.Inspectors._extends … with org.scalatest.Inspectors才能将forAtLeast放入作用域。

如果您想避免检查器使用循环样式语法,可以将检查器简写语法与基于反射的have语法一起使用:

atLeast(1, reasons.items) must have ('status "ACTIVE")
atLeast(1, reasons.items) must have ('status "INACTIVE")

如果您想避免have的基于反射的语法,可以扩展have语法以直接支持status属性:

def status(expectedValue: String) =
new HavePropertyMatcher[Item, String] {
def apply(item: Item) =
HavePropertyMatchResult(
item.status == expectedValue,
"status",
expectedValue,
item.title
)
}
atLeast(1, reasons.items) must have (status "ACTIVE")
atLeast(1, reasons.items) must have (status "INACTIVE")

或者,如果您更喜欢be而不是have,则可以扩展be语法以添加对activeinactive:的支持

class StatusMatcher(expectedValue: String) extends BeMatcher[Item] {
def apply(left: Item) =
MatchResult(
left.status == expectedValue,
left.toString + " did not have status " + expectedValue,
left.toString + " had status " + expectedValue,
)
}
val active = new StatusMatcher("ACTIVE")
val inactive = new statusMatcher("INACTIVE")
atLeast(1, reasons.items) must be (active)
atLeast(1, reasons.items) must be (inactive)

在这里的例子中,仅仅为了在断言中保存几个单词而定义自己的匹配器看起来有点傻,但如果你写了数百个关于相同属性的测试,那么将断言压缩到一行仍然是自然可读的,这真的很方便。根据我的经验,如果你在很多测试中重用它们,那么像这样定义你自己的匹配器是有意义的。

干净的方法是

val active = reasons.items.exists(item => item.status == "ACTIVE")

或更短的

val active = reasons.items.exists(_.status == "ACTIVE")

val inactive类似。这确实存在在列表中迭代两次的问题(但与代码中不同的是,两次都是在找到合适的项后停止(。

对于"至少1",可以在items上使用exists,CCD_15检查给定的谓词,如果至少有一项满足条件,则返回true。对于"ACTIVE和INACTIVE",您可以使用&amp;。

reasons.items.exists(_.status.equals("ACTIVE")) && reasons.items.exists(_.status.equals("INACTIVE"))`

最新更新