This Scala code populates a list with objects:
// fairly standard var people = List[Person]() for (i <- 1 to 10) { people = new Person(i) :: people }
So does this.
// slightly more functional val people = (List[Person]() /: (1 to 10)) {(people, i) => new Person(i) :: people }
If you’re a Java programmer and just balked, you’re probably not alone. I know what it does and I have to read it from left to right to left to right again. In this case the shortcut’s a Scala mental snag equivalent to Java code like:
boolean empty = (!list.empty()) ? false : true;
There’s always going to be a pause when you read stuff like this. Remove the operator weirdness and you get:
val people = (1 to 10).foldLeft(List[Person]()) {(people, i) => new Person(i) :: people }
At least here, the reader doesn’t have to catch on to the flipping of the object and the method argument done by the /: method. In time, you probably get used to reading shortcut operators, but more than likely you’re going to be snagging for a while, and so will the next guy reading your code.
Just because you can do something, doesn’t mean you should 🙂
Update:
Thanks to @jstrachan for this:
val people = (1 to 10).map(new Person(_))
I have much to learn 🙂