嵌套选项的惯用Scala
假设我有一个元素对象(实际上来自JDom)。它可能有一个名为“Group”的子元素,也可能没有。如果有,那么它可能有一个名为“ID”的属性,或者也可能没有。我想要ID值(如果存在) 如果Java我会写嵌套选项的惯用Scala,scala,Scala,假设我有一个元素对象(实际上来自JDom)。它可能有一个名为“Group”的子元素,也可能没有。如果有,那么它可能有一个名为“ID”的属性,或者也可能没有。我想要ID值(如果存在) 如果Java我会写 private String getId(Element e) { for (Element child : e.getChildren()) if (child.getName().equals("Group")) for (Attribute a : child.g
private String getId(Element e) {
for (Element child : e.getChildren())
if (child.getName().equals("Group"))
for (Attribute a : child.getAttributes())
if (a.getName().equals("ID"))
return a.getValue();
return null;
}
在斯卡拉我也有
val id = children.find(_.getName == "Group") match {
case None => None
case Some(child) => {
child.getAttributes.asScala.find(_.getName == "ID") match {
case None => None
case Some(a) => Some(a.getValue)
}
}
}
或
他们的哪一个,或者第三个,更惯用呢
val idOption = children
.find(_.getName == "Group")
.flatMap(_.getAttributes.asScala.find(_.getName == "ID"))
或者,为了便于理解,请:
val idOption =
for {
child <- children.find(_.getName == "Group")
id <- child.getAttributes.asScala.find(_.getName == "ID")
} yield id
val选项=
为了{
有人做了一个镜头回答。我喜欢平面图,基本上阻止了选项嵌套。理解像这样的理解很容易。太棒了!
val idOption =
for {
child <- children.find(_.getName == "Group")
id <- child.getAttributes.asScala.find(_.getName == "ID")
} yield id