假設我有一個字符串s,如果我要算標籤的字符串中我能做的金額如下:Scala string.count(' t'==)它爲什麼會起作用?
string.count('\t'==)
任何想法,爲什麼這個工程?我會一直期待的謂詞
參考:Count all occurrences of a char within a string
假設我有一個字符串s,如果我要算標籤的字符串中我能做的金額如下:Scala string.count(' t'==)它爲什麼會起作用?
string.count('\t'==)
任何想法,爲什麼這個工程?我會一直期待的謂詞
參考:Count all occurrences of a char within a string
的==
被用作「後綴運算符」,這樣你實際上在功能'\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
明白了,謝謝! – cvargascr
但嘗試在REPL中輸入''\ t'。=='。你說你正在傳遞一個函數,但是混合中有超載和eta擴展。預期的類型是至關重要的。現在我必須upvote b/c upvoted其他答案。 –
在Scala中,你可以通過謂語這樣:
def predicate(ch: Char) = { ... }
string.count(ch => predicate(ch))
或這種方式
string.count(predicate(_))
也有辦法忽略參數佔位符,它看起來確實不錯
string.count(predicate)
而在你的例子中,你實際上是調用方法「==」字符,所以它非常類似於上面的代碼。更難以理解。
string.count('\t'.==)
是你的問題
count(p: (Char) ⇒ Boolean): Int
?==
方法是另一個char上的布爾函數嗎?答案:是的,是的。
多好的答案,但我明白他們爲什麼稱你爲'Malvolio'。 –
''\ t'=='是'ch =>'(某種程度上不可讀的)等價物'\ t'== ch' – Martijn