Farid Zakaria

Archive 1 min read

Scala Closure Example


This post comes from my original WordPress blog, written between 2009 and 2018. It is kept here verbatim as an archive — the formatting did not always survive the move, and I no longer agree with all of it.

Somewhat more real example

Closures aren't new to me. I've used them a bunch when I've done JavaScript however I felt like the concept of a closure was really well defined/understood in JavaScript. Although I was aware you could likely (wasn't sure until I google'd) do it Scala, every example online infuriated me!
Every example was pretty trivial (i.e. summing function) and used a global variable.
I wanted to give a better example!

Example


import org.joda.time.{DateTime,Period}

//We are inside some class or object
private def filterThoseCreatedBefore( time : DateTime) : (Model) => Boolean = {
  (model : Model)  =>  {
    model.createdAt.isBefore(time)
  }
}

val FILTER_CREATED_TWO_WEEKS_AGO = 
      filterThoseCreatedBefore(DateTime.now.minus(Period.weeks(2)))

val filteredTwoWeekList = models.filter(FILTER_CREATED_TWO_WEEKS_AGO(_))