Like LINQ in C#, for comprehension in Scala, anything similar in Kotlin? If not supported, is it planned?
In the preview version of Kotlin 1.1 there's universal async
/await
syntax which can be used for different kinds of monadic comprehensions:
Many languages (starting with C# in 2012) support asynchronous programming through dedicated language constructs such as async/await keywords. In Kotlin, we generalized this concept so that libraries can define their own versions of such constructs, and async is not a keyword, but simply a function.
This design allows for integration of different asynchronous APIs: futures/promises, callback-passing, etc. It is also general enough to express lazy generators (yield) and cover some other use cases.
source
There is no special keyword (do/for) and so no direct translation to nested flatMap (desugaring) like in other languages.
But monadic comprehension can be implemented with coroutines.
From Arrow documentation : https://arrow-kt.io/docs/patterns/monad_comprehensions/#comprehensions-over-coroutines
Comprehensions over coroutines
This feature is known with multiple names: async/await, coroutines, do notation, for comprehensions…each version contains certain unique points but all derive from the same principles. In Kotlin, coroutines (introduced in version 1.1 of the language) make the compiler capable of rewriting seemingly synchronous code into asynchronous sequences. Arrow uses this capability of the compiler to bring you coroutines-like notation to all instances of the Monad typeclass.
This means that comprehensions are available for Option, Try, List, Reader, Observable, Flux or IO all the same.
For coroutines, see also "Deep dive into Coroutines on JVM @ KotlinConf 2017" : https://www.slideshare.net/elizarov/deep-dive-into-coroutines-on-jvm-kotlinconf-2017?next_slideshow=1
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