Saturday, December 31, 2011

Scala closures vs Guava collection functions

Let me show you the same method using list transformations (aka "map" in functional programming speak), one in Java programming language:

    @GET @Path("user/{userId}/likes") @Produces(MediaType.APPLICATION_JSON)
    public Payload<Iterable<Map<String, Object>>> getUserLikes(@PathParam("userId") long userId) {
        User user = neo4j.findOne(userId, User.class);
        Iterable<Interest> likeInterests = user.getLikeInterests();
        Iterable<Map<String, Object>> likes = Iterables.transform(likeInterests, new Function<Interest, Map<String, Object>>() {
            public Map<String, Object> apply(Interest interest) {
                HashMap<String, Object> row = new HashMap<String, Object>();
                row.put("id", interest.getNodeId());
                row.put("name", interest.getName());
                return  row;
        return new Payload<Iterable<Map<String, Object>>>(likes);

And one in Scala programming language :

    @GET @Path("user/{userId}/likes") @Produces(Array(MediaType.APPLICATION_JSON))
    def getUserLikes(@PathParam("userId") userId: Long): Payload[Iterable[Map[String, Object]]] = {
        val user = neo4j.findOne(userId, classOf[User])
        val likeInterests = user.getLikeInterests
        val likes = =>
          Map("id"->interest.getNodeId, "name"->interest.getName) )
        new Payload(likes)

Is Scala hard to read? I'll leave it to you to decide. :-)

To learn more about Scala programming, I recommend Programming in Scala: A Comprehensive Step-by-Step Guide, 2nd Edition.


  1. This comment has been removed by the author.

  2. In a coding dojo a couple of years ago we tried a similar exercise but comparing lamdaj and Scala -

    I think a language which has the ability to pass around functions/delegates as a first class citizen is always going to make it easier to write cleaner code than one where you have to hack it by using an anonymous class.

    Scala is particularly good in that respect as you've proved with your code examples.