How to apply a callback to an array (apply a function to each element) in Scala

3 Answers

0 votes
// Using map 

object CallbackExample extends App {

  // Callback: takes an Int and returns an Int
  def double(x: Int): Int = x * 2

  val numbers = Array(5, 10, 15, 20)

  // Apply the callback to each element
  val doubled = numbers.map(double)

  println(doubled.mkString(", "))
}



/*
run:

10, 20, 30, 40

*/

 



answered Mar 21 by avibootz
0 votes
// Using an inline lambda callback

object CallbackExample extends App {

    val numbers = Array(5, 10, 15, 20)

    val tripled = numbers.map(x => x * 3)

    println(tripled.mkString(", "))
}



/*
run:

15, 30, 45, 60

*/

 



answered Mar 21 by avibootz
0 votes
// Using foreach (in‑place updates)

// use foreach to do something with each element 
// rather than return a new array.

object CallbackExample extends App {

    val numbers = Array(5, 10, 15, 20)

    // Modify the array in place
    numbers.indices.foreach { i =>
      numbers(i) = numbers(i) * 2
    }

    println(numbers.mkString(", "))
}


/*
run:

10, 20, 30, 40

*/

 



answered Mar 21 by avibootz
...