Like LINQ in C#, for comprehension in Scala, anything similar in Kotlin? If not supported, is it planned?
-
6I think, there has been some miscommunication here. There's no such policy as not to use monads anywhere. Some monad-like constructs, such as safe calls for nullable types, are built into the language. We do not support comprehensions at the moment, but this feature is on the table.– Andrey BreslavDec 17, 2015 at 8:34
-
As @AndreyBreslav noted, Kotlin does use monadic constructions where it makes sense. What I said in my answer is that there is no goal to use monads in every single language concept– voddanDec 17, 2015 at 9:51
2 Answers
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
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.