Skip to content

Instantly share code, notes, and snippets.

@leontabak
Created October 6, 2021 18:40
Show Gist options
  • Save leontabak/7eced1f3cc4e3bd025448ab1d5a2c622 to your computer and use it in GitHub Desktop.
Save leontabak/7eced1f3cc4e3bd025448ab1d5a2c622 to your computer and use it in GitHub Desktop.
Another example of the use of a closure in Scala.
package com.eonsahead
object HelloGoodbye extends App {
def greetingMaker (): () => String = {
// This is a function that returns a function
// to its caller.
// This function ("greetingMaker") has one local
// variable (named "arriving").
var arriving = true
// The definition of "greetingMaker" contains
// the definition of another function ("greeting").
// This is the function that "greetingMaker" will
// return to its caller.
def greeting (): String = {
// This function ("greeting") lies within the
// scope of the variable "arriving" that we defined
// in the "greetingMaker" function.
// Let the value of "arriving" determine how
// we will greet our friend this time: "Hello"
// or "Goodbye" ?
val result = if( arriving ) "Hello" else "Goodbye"
// Remember whether we were coming or going
// the last time we greeted our friend.
arriving = !arriving
// Return the string "Hello" or "Goodbye"
// as appropriate.
result
} // end of greeting()
greeting
} // end of greetingMaker
// Create a function and store it in
// a variable.
val fun = greetingMaker()
for( n <- 0 until 8) {
// Repeatedly call the function that we created.
// The successive calls return "Hello"
// and "Goodbye" alternately.
// The function has a memory!
println( fun() )
}
} // HelloGoodbye
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment