Skip to content

Instantly share code, notes, and snippets.

@JoolsF
Created November 24, 2016 10:54
Show Gist options
  • Select an option

  • Save JoolsF/3967453b4d23d3e616943dcb812bafdb to your computer and use it in GitHub Desktop.

Select an option

Save JoolsF/3967453b4d23d3e616943dcb812bafdb to your computer and use it in GitHub Desktop.
Scala closure basics
/**
* A closure is a function, whose return value depends on the value of one or more variables
* declared outside this function.
*/
/*
* Example 1
* closureIdentity has a reference to the variable i outside the function but in the enclosing scope.
* The function references factor and reads its current value each time.
*/
var i = 1
val closureIdentity = () => i
closureIdentity() // 1
i = 2
closureIdentity() // 2
i = -90
closureIdentity() // -90
/*
* Example 2
* Identical situation but shown with a def
*/
var j = 1
def jId = j
jId // 1
j = 2
jId // 2
j = -90
jId // -90
/*
* Example 3 - initialising the closed-over variable inside the value declaration
*/
val closureIncrement: () => Int = { var offset = 0; () => { offset += 1; offset }}
closureIncrement() // 1
closureIncrement() // 2
closureIncrement() // 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment