我正在尝试在Scala中实现一个递归方法,并遇到可变性问题(我是Scala的新手):
def findMembersRecursive(path : String, members : Set[String]) : Unit = {
val candidates : Set[String] = candidateService.getProspectiveCandidates(path)
candidates.foreach { candidate =>
if(candidate.endsWith("hello")) {
members ++= candidate
} else {
findMembersRecursive(candidate, members)
}
}
}
所以我们的想法是,当我们递归执行时,这组字符串(members
)会增长。
此处不允许我将candidate
添加到members
,因为members
似乎是不可变的。关于如何重构代码以递归工作的任何想法?
答案 0 :(得分:1)
我会这样实现这个功能:
def findMembersRecursive(path: String): Set[String] =
candidatesService
.getProspectiveCandidates(path)
.flatMap {
case candidate if candidate.endsWith("hello") => Set(candidate)
case candidate => findMembersRecursive(candidate)
}