价值 || 不是 String 的成员 - scala

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31127409/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 07:18:53  来源:igfitidea点击:

value || is not a member of String - scala

scala

提问by Naren

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?

过滤某些词。但是我收到编译错误,说 - value||不是String. 谁能告诉我我哪里出错了?

回答by Ben Reich

The method containson Stringtakes a Stringas an argument:

containson方法String将 aString作为参数:

"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.

因此,编译器试图解释"I" || "sam"为 a String,因为这是 的参数contains。在 Scala 中,此语句等效于"I".||("sam")(调用||on的方法"I")。由于没有方法||String,这无法编译。

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

你可能的意思是!(word.contains("I") || word.contains("sam")). 这是有道理的,因为我们现在呼吁||Boolean是由返回word.contains("I"),并且||是一个方法Boolean(如记录在这里)。所以你的整个陈述可能是:

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))