0

Consider the following code,

 1 var ip = ArrayBuffer[String]()
 2 ip += "1"
 3 println(ip)
 4 ip.clear()
 5 (1 to 10).foreach(ip += ("1"))
 6 println(ip)

Here in line no: 5 using variable ip inside higher order function results in exception. I do know using var is not advisable but I want to know how to use vars inside higher order functions. Or is there an alternative to mange state.

Hariharan
  • 881
  • 1
  • 13
  • 25
  • If you want to go the mutable route, just use a for loop: `for (_ <- 1 to 10) ip += "1"` – Lasf Nov 12 '18 at 16:15

1 Answers1

3

The following works:

(1 to 10).foreach(_ => ip += "1")

foldLeft is more functional and you can dispense with mutable state:

(1 to 10).foldLeft(List.empty[String]){
  case (acc, _) => "1" :: acc
}

Output:

List[String] = List(1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
Terry Dactyl
  • 1,839
  • 12
  • 21