Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid mutable variable in scala

Tags:

for-loop

scala

I have a piece of code like this

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

The compiler gives a warning that its not good practise to use a mutable variable. How do I avoid this ?

Disclaimer: I used a variant of this code in an assignment and the submission is done. I would like to know what the right thing to do is

like image 629
rakeshr Avatar asked Jun 21 '26 08:06

rakeshr


1 Answers

You could do:

def filter(t:String) = listofStrings.exists(t.contains(_))
like image 173
Eduardo Avatar answered Jun 23 '26 06:06

Eduardo