Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

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

FlexNet Code Aware, a free scan tool for developers. Scan Java, NuGet, and NPM packages for open source security and open source license compliance issues.

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:


 Scan Java, NuGet, and NPM packages for open source security and license compliance issues. 

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

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}