Scala Currying and function literals

  • A+

I was reading the-neophytes-guide-to-scala-part-10 where I came across following code.

type EmailFilter = Email => Boolean  val minimumSize: Int => EmailFilter = n => email => email.text.size >= n 

I understood the first line where type alias EmailFilter is created for a function which takes email return boolean. But I don't understand the second line where we take email and number as input and returns boolean by checking size. Please decode the second line and explain me this syntactic sugar code for the function.

There is no syntactic sugar whatsoever, just raw lambda expressions. If you plug in the type EmailFilter definition into the type in the second line, you obtain

Int => (Email => Boolean) 

which is the same (because of right-associativity of =>) as

Int => Email => Boolean  

and this corresponds perfectly with

n   => email => (email.text.size >= n) 

which essentially just says: given a number n, create an email filter that, given an email returns true if and only if the length of the email is at least n, so that, for example


returns a closure that behaves just like

email => email.text.size >= 100 

i.e. it filters all emails with length greater than or equal 100. Thus, with suitably defined example mails shortMail and longMail, you would obtain:

minimumSize(100)(shortMail) // false minimumSize(100)(longMail) // true 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: