我有一段像这样的代码
def filter(t: String) : Boolean = {
var found = false;
for(s <- listofStrings) {
if ( t.contains(s)) { found = true}
}
found
}
编译器发出警告,说明使用可变变量并不是一个好习惯。我该如何避免这种情况?
免责声明:我在作业中使用了此代码的变体,并完成了提交。我想知道正确的做法是
答案 0 :(得分:8)
你可以这样做:
def filter(t:String) = listofStrings.exists(t.contains(_))
答案 1 :(得分:3)
如果您使用尽可能少的内置集合函数,请使用递归:
def filter(t: String, xs: List[String]): Boolean = xs match {
case Nil => false
case x :: ys => t.contains(x) || filter(t, ys)
}
println(filter("Brave New World", List("few", "screw", "ew"))) // true
println(filter("Fahrenheit 451", List("20", "30", "80"))) // false