Scala Closure Example

Published 2014-07-09 on Farid Zakaria's Blog

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(_))