假设我有一个字符串s,如果我想计算字符串中的标签数量,我可以执行以下操作:
string.count('\t'==)
知道为什么会这样吗?我会期待一个谓词
答案 0 :(得分:4)
==
被用作"后缀运算符",因此您实际上将函数'\t'.==
传递给string.count
。
注意:如果我在打开-feature
的REPL中执行此操作,我会收到此输出:
scala> "hello\tworld".count('\t'==)
<console>:8: warning: postfix operator == should be enabled
by making the implicit value language.postfixOps visible.
This can be achieved by adding the import clause 'import scala.language.postfixOps'
or by setting the compiler option -language:postfixOps.
See the Scala docs for value scala.language.postfixOps for a discussion
why the feature should be explicitly enabled.
"hello\tworld".count('\t'==)
^
> res0: Int = 1
添加点会删除警告:
scala> "hello\tworld".count('\t'.==)
res1: Int = 1
答案 1 :(得分:2)
你的问题是
count(p: (Char) ⇒ Boolean): Int
?==
方法是否是另一个char上的布尔函数?答案:是的,是的。
答案 2 :(得分:1)
在scala中,您可以通过这种方式传递谓词:
def predicate(ch: Char) = { ... }
string.count(ch => predicate(ch))
或者这样
string.count(predicate(_))
还有一种方法可以省略参数占位符,看起来很不错
string.count(predicate)
在你的例子中,你实际上正在调用Char的方法'==',所以它与上面的代码非常相似。更难以理解。
string.count('\t'.==)