Possible Duplicate:
Can anyone explain how the symbol “=>” is used in Scala
val list = List("abc", "cde", "fg")
list.count (s => s.length == 3)
The above code snippet returns the number of string elements in list whose length is equal to 3. But I’m not able to understand the snippet as I’m having trouble to grasp the usage of the => operator in this context. Any explanation will be realy helpful.
Yeah, Scala can be pretty hard to understand. I’ll do my best to explain it, though I might not get it right either.
The
List.countmethod takes as a parameter ablockof code that returns a boolean.Blocks are just little snippets of code and can be created in many ways eg by enclosing code in
{ }In the scala docs this is described as
so
counttakes a parameterpwhich is a block that takes an argument of typeAand returns aBooleanSo in this example:
is a
blockof code. Blocks usually follow the formatSo in this instance
sis the input to the block ands.length == 3is the code that should return a boolean. You can name the arguments whatever you like, so long as they are in the correct order.When using a method that iterates over a collection, eg
count,map,each, etc, the argument passed will be the current item in the collection it is iterating over.If you want to learn more about it you should check out the Coursera course that is being run my Martin Odersky (the creator of scala) and will be covering details like this in great detail: https://www.coursera.org/course/progfun