Debugging functional code in Scala

I think everybody’s advice to break this thing down to more manageable chunks is the best approach. One trick for debugging smaller expressions is to steal Ruby’s tap function, as described here. “tap” allows you to stick an expression in the middle of a chain like this, and perhaps print out some debug values, like so:

val ls = List(1,2,3).map(_ * 2)
                .tap(soFar => println("So far: " + soFar))
                .map(_ * 2)
println(ls)

This will print out:

So far: List(2, 4, 6)
List(4, 8, 12)

It helps me every once in a while.

Leave a Comment