Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

value || is not a member of String - scala

Tags:

scala

I am using string filter function like:

val strings = List("hi","I","am","here") //this list is a stream of words from Twitter
val mystrings = strings.filter(word => !word.contains("I" || "sam") // I need filter out certain stop words

to filter certain words. But I am getting compilation error saying that - value || is not a member of String. Can anybody tell me where I am going wrong?

like image 231
Naren Avatar asked Dec 05 '25 14:12

Naren


1 Answers

The method contains on String takes a String as an argument:

"foo".contains("foo") //True

So, the compiler is trying to interpret "I" || "sam" as a String, since that is the argument to contains. In Scala, this statement would be equivalent to "I".||("sam") (calling the || method on "I"). Since there is no method || on String, this fails to compile.

What you probably meant is !(word.contains("I") || word.contains("sam")). This makes sense, since we are now calling || on the Boolean that is returned by word.contains("I"), and || is a method on Boolean (as documented here). So your whole statement might be:

strings.filter(word => !(word.contains("I") || word.contains("sam"))

Which is also equivalent to:

strings.filter(word => !word.contains("I") && !word.contains("sam"))

If you end up with a lot of phrases to filter, you could also flip it around:

val segments = Set("I", "sam")
strings.filter(word => segments.forall(segment => !word.contains(segment)))
//Equivalent
strings.filter(word => !segments.exists(word.contains))
like image 65
Ben Reich Avatar answered Dec 07 '25 08:12

Ben Reich