避免在scala中使用可变变量

时间:2012-10-12 07:13:50

标签: scala for-loop

我有一段像这样的代码

def filter(t: String) : Boolean = {
    var found = false;
    for(s <- listofStrings) {
      if ( t.contains(s)) { found = true}
    }
    found
  }

编译器发出警告,说明使用可变变量并不是一个好习惯。我该如何避免这种情况?

免责声明:我在作业中使用了此代码的变体,并完成了提交。我想知道正确的做法是

2 个答案:

答案 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
相关问题