So in a comment from another question, I just saw this example for counting the number of L’s in a string:
"hello".count('l'==)
And crazy enough..it works.
Starting with the fully expanded version, we have:
"hello".count(ch => ch == 'l')
Which can then be reduced to:
"hello".count(_ == 'l')
But then we can do:
"hello".count('l'==)
And I’m going like … ??? …
Presumably Scala is inferring that we must have meant to add an _ at the end of the comparison. IMO, this is where things start getting super weird; this seems overboard to me. Can anyone explain the thinking behind allowing this syntax, or shed further light on this?
If you think this is cool, then how do we justify not assuming that people may want the == operator too, so that could be omitted? Then we could have:
"hello".count('l')
I think I’m having flashbacks to the nightmare of having 10^99999 possible ways of doing things in perl…
The “fully expanded” version you started out with is actually backwards, it should be:
However,
==isn’t considered special by the Scala language, it’s just another method ofAny. So to expand even further:But hang on… The
countmethod fromTraversableOnceis expecting a function with the signature(A) ⇒ Booleanas an argument. The signature ofAny.==()happens to beAny ⇒ Boolean, so that fits neatly without needing to be wrapped in another anonymous function. So instead we can just say:or, omitting the dots:
Why don’t we omit the
==operator too? Well, I guess you could definecountEqualascount(a => a ==)(or, more succinctly,count(_ ==)) if you really wanted to… But you could just as well definecountLowerCaseor whatever. The main point here is that==isn’t special.