How to use closure in Scala

4 Answers

0 votes
object Main {
  def main(args: Array[String]): Unit = {

    val x: Int = 10
    val y: Int = 20

    // This anonymous function captures x and y from the surrounding scope.
    // Because it "remembers" these values, it is a closure.
    val add: () => Int = () => x + y

    val result: Int = add()

    println(result)
  }
}



/*
run:

30

*/

 



answered Jun 3 by avibootz
0 votes
// Closures capture variables by reference

object Main {
  def main(args: Array[String]): Unit = {

    var counter: Int = 0

    // Closure capturing and modifying "counter"
    val inc: () => Unit = () => {
      counter += 1
    }

    inc()
    inc()

    println(counter)
  }
}


/*
run:

2

*/

 



answered Jun 3 by avibootz
0 votes
// Closures with parameters

object Main {
  def main(args: Array[String]): Unit = {

    val factor: Int = 3

    // Closure capturing "factor"
    val multiply: (Int, Int) => Int = (a: Int, b: Int) => (a + b) * factor

    println(multiply(5, 5))
  }
}


/*
run:

30

*/

 



answered Jun 3 by avibootz
0 votes
// Closures inside collection operations

object Main {
  def main(args: Array[String]): Unit = {

    val nums: List[Int] = List(1, 2, 3)
    val factor: Int = 2

    // map uses a closure that captures "factor"
    val doubled: List[Int] = nums.map(n => n * factor)

    println(doubled)
  }
}


/*
run:

List(2, 4, 6)

*/

 



answered Jun 3 by avibootz

Related questions

4 answers 38 views
4 answers 50 views
5 answers 49 views
4 answers 43 views
3 answers 40 views
...