Does Kotlin support monadic comprehension?

穿精又带淫゛_ 提交于 2021-02-07 11:23:14

问题


Like LINQ in C#, for comprehension in Scala, anything similar in Kotlin? If not supported, is it planned?


回答1:


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




回答2:


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



来源:https://stackoverflow.com/questions/34248483/does-kotlin-support-monadic-comprehension

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!