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 Kotlin

2 Answers

0 votes
// Using map
 
fun double(x: Int): Int = x * 2
 
fun main() {
    val numbers = arrayOf(5, 10, 15, 20)
 
    // Apply the callback to each element
    val doubled = numbers.map(::double)
    
    // returns a new list, leaving the original array unchanged.
 
    println(doubled)   
}
 
 
/*
run:
 
[10, 20, 30, 40]
 
*/
 

 



answered 4 days ago by avibootz
0 votes
// Using an inline lambda callback

fun main() {
    val numbers = arrayOf(5, 10, 15, 20)

    val tripled = numbers.map { x -> x * 3 } // expressive

    println(tripled)  
}



/*
run:

[15, 30, 45, 60]

*/

 



answered 4 days ago by avibootz
...