4 ms·
There is no need to feel small. It is just using declarative constructs that require imperative code in non-functional languages. A great blog entry about gett
by BonoboBoner 16y ago
There is no need to feel small. It is just using declarative constructs that require imperative code in non-functional languages.
A great blog entry about getting started with all of this is the following: http://blog.stefandeboey.be/34563653 http://blog.stefandeboey.be/34563653
The author shows a functional way of achieving something and afterwards shows the Java-version of the same code.
As an example, say you have a List of Person-objects:
persons.foreach({ p => println(p.name) })
is the same as
for (p : persons)
System.out.println(p.name);
What if you want to extract the persons name and have them as a list?
persons.map({ p => p.name })
the imperative version:
Collection<String> names = new ArrayList<String>();
for (p : persons)
names.add(p.name);
Note that you can omit the "." and "(",")" for method invocations in Scala, because the compiler will add them automatically.
This means that
persons.foreach({ p => println(p.name) })
can be reduced to the following:
persons foreach { p => println(p.name) }
Another nice addition is the fact that Scala adds a "default variable name" that represents current element of the colleciton you're iterating over. The variable to use is the underscore "_". This means the code can be even more concise:
persons map { _.name }
As seen above the map function is used to somewhat transform one data-representation (the persons list) into another (a list of names of these persons.
All you need to do to achieve this, is supply a function that helps this transformation process to perform the actual transformation step. The power lies within the fact that you dont need to give a damn about how to iterate over the persons list. You just tell Scala the "WHAT" and now the "HOW".
All that being said, for more information on the subject, you should definetly check out the blog post mentioned above. It does a great job at explaining this in more detail and with other examples.