Scala vs Java manipulating collections
One of the nicest scala features is for comprehension loops. They allow you to express the expected outcome of the loop and manipulate Seq, List and other collections in a way that saves time and removes clutter from its Java counterpart.
Consider the following…
The Java code is just straightforward iterate over the collection, turn its values to ints and then check if the int is even before we add it to a new collection. Both of the scala code result in the same result a List[Int] of even numbers. Depends on your style or the logic involved you can take several approaches.- Go for the yield style where as you iterate over a collection with a for comprehension and a guard the yield sends new elements to the resulting List.
- Use the map and filter FP style approach where you map the collection to a new collection of Ints that is then filtered and yields a new collection of even ints.
- Check out some other ways to do the same task more efficiently in scala as well contributed by some members on the G+ Scala community
