Closures in Scala [Video]

DZone's Guide to

Closures in Scala [Video]

If you're trying Scala out, see how closures work to bind free variables to function literals with some sample code and a video.

· Java Zone
Free Resource

Learn how to troubleshoot and diagnose some of the most common performance issues in Java today. Brought to you in partnership with AppDynamics.

Before we begin discussing closures in Scala, let us have a quick look at a function. The function literal bill below accepts only one input parameter: netBill. However, the function calculates the final bill by adding a service charge to netBill.

val bill = (netBill: Double) => netBill*(1 + serviceCharge/100)


So if we try to compile the above function, Scala is going to complain that it does not know anything about serviceCharge.

We have one bounded variablenetBill. It is bound to the function call and takes its value from whatever is provided to the function. But serviceCharge is a free variable and the function literal does not provide it with any value.

In order to execute our function literal, we need to provide a value to serviceCharge outside of the function bill.

val serviceCharge = 14


And now, if we redefine our bill function again, then Scala will be quite happy with our declaration.

The function value created at runtime from this function literal bill is called a closure because we capture the binding of its free variable by closing the function. In the above example, we have captured the value of serviceCharge as 14.

Please refer to the video below to understand the concept in more detail and to check out few more examples:


Understand the needs and benefits around implementing the right monitoring solution for a growing containerized market. Brought to you in partnership with AppDynamics.

DOWNLOAD
Topics:
scala ,functional programming ,closure ,java ,tutorial

Opinions expressed by DZone contributors are their own.