Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

40,393 questions

52,502 answers

573 users

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 4 days ago 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 4 days ago 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 4 days ago by avibootz
...