In Scala, one can easily do a parallel map, forEach, etc, with:
collection.par.map(..)
Is there an equivalent in Kotlin?
Kotlin's Coroutines enabling you to write parallel code easily, in a sequential way, and without worrying about the contextual overheads you know from using threads in Java.
When you extend your development experience from Android to Kotlin Multiplatform Mobile, you will encounter a different state and concurrency model for iOS. This is a Kotlin/Native model that compiles Kotlin code to native binaries that can run without a virtual machine, for example on iOS.
Creating a thread in Kotlin is similar to doing so in Java.class SimpleThread: Thread() { public override fun run() { println("${Thread. currentThread()} has run.") } } Or we can implement the Runnable interface: class SimpleRunnable: Runnable { public override fun run() { println("${Thread.
The Kotlin standard library has no support for parallel operations. However, since Kotlin uses the standard Java collection classes, you can use the Java 8 stream API to perform parallel operations on Kotlin collections as well.
e.g.
myCollection.parallelStream() .map { ... } .filter { ... }
As of Kotlin 1.1, parallel operations can also be expressed quite elegantly in terms of coroutines. Here is pmap
on lists:
fun <A, B>List<A>.pmap(f: suspend (A) -> B): List<B> = runBlocking { map { async(CommonPool) { f(it) } }.map { it.await() } }
Note that coroutines are still an experimental feature.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With