2015-06-16 14 views

回答

4

==被用作「後綴運算符」,這樣你實際上在功能'\t'.==傳遞給string.count

注:如果我在REPL做到這一點與-feature打開,我得到這樣的輸出:

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 
+0

明白了,謝謝! – cvargascr

+0

但嘗試在REPL中輸入''\ t'。=='。你說你正在傳遞一個函數,但是混合中有超載和eta擴展。預期的類型是至關重要的。現在我必須upvote b/c upvoted其他答案。 –

1

在Scala中,你可以通過謂語這樣:

def predicate(ch: Char) = { ... } 

string.count(ch => predicate(ch)) 

或這種方式

string.count(predicate(_)) 

也有辦法忽略參數佔位符,它看起來確實不錯

string.count(predicate) 

而在你的例子中,你實際上是調用方法「==」字符,所以它非常類似於上面的代碼。更難以理解。

string.count('\t'.==) 
2

是你的問題

  • 確實字符串有一個函數count(p: (Char) ⇒ Boolean): Int
  • 是一個char上的==方法是另一個char上的布爾函數嗎?

答案:是的,是的。

+0

多好的答案,但我明白他們爲什麼稱你爲'Malvolio'。 –

相關問題