I would like to propose an annotation to create wr...
# language-proposals
a
I would like to propose an annotation to create wrappers around
suspend
functions for use outside of Kotlin code. Example of creating a
suspend
function and exposing it as a `CompletableFuture`:
Copy code
suspend fun getMarketTaxRates(world: World): Map<City, Byte> {
    doStuff()
}

@JvmName("getMarketTaxRates")
fun getMarketTaxRatesAsync(world: World) = GlobalScope.future {
    getMarketTaxRates(world)
}
The function appended with
Async
doesn't do anything beyond wrapping another
suspend
function within a
GlobalScope.Future
. As an annotation this could look like:
Copy code
@JvmFuture
suspend fun getMarketTaxRates(world: World): Map<City, Byte> {
    doStuff()
}
which could automatically generate the wrapper function with
@JvmName
set to the name of the original function.
This could be problematic when function overloading is used on JS (where function overloading isn't supported), so the annotation could take a parameter to override the name of the generated function.
Copy code
@JvmFuture @JsPromise("getMarketTaxRatesForWorld")
suspend fun getMarketTaxRates(world: World): Map<City, Byte> {
    doStuff()
}
Thinking about it, this isn't a new issue and would probably be handled by the existing
@JsName
annotation (and
@JvmName
)
d
Could definitely implement this now with a compiler plugin.
r
There is also https://github.com/ForteScarlet/kotlin-suspend-transform-compiler-plugin . I have used both and the main issue I have is that I need to expose
suspend
functions as callable from other languages/envs JS, Java, Native with C interop and WASM. None of these plugins or the lang seems to get this right at the moment in terms of ergonomics or cancellation wiring with the coroutines system. I'd expect this kind of functionality coming from the lang and not a community plugin since this interop is important in KMP both at the platform level but also from the point of view of consuming Kotlin binaries in other languages. xef.ai support for Java, Scala and WASM has been temporarily dropped until we have a solution to call suspend functions in those places. All our stack which includes Ktor, Arrow, Serialization and calls to LLMs via suspend functions are unusable from those languages without complex wrappers and unchecked casts written in the other languages. We attempted to codegen and add wrappers for those languages but the code to make it work it was often larger than the ops it was wrapping. In the JVM there is also other considerations, just turning
suspend
into Futures it's not ideal when you run in JVM's with LOOM support. In those cases we want
suspend
functions to work same as kotlin without being wrapped in Future and working together with LOOM's cancellation.